Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. public class Test implements Savable<Test>{
  2.    
  3.     public String name;
  4.     public int count;
  5.     public float x, y;
  6.    
  7.     public Test(){
  8.         //Empty constructor for loading
  9.     }
  10.    
  11.     public Test(String name, int count, float x, float y){
  12.         this.name = name;
  13.         this.count = count;
  14.         this.x = x;
  15.         this.y = y;
  16.     }
  17.    
  18.     public void save(DataOutputStream out) throws IOException{
  19.         out.writeUTF(name);
  20.         out.writeInt(count);
  21.         out.writeFloat(x);
  22.         out.writeFloat(y);
  23.     }
  24.    
  25.     public Test load(DataInputStream in) throws IOException{
  26.         name = in.readUTF();
  27.         count = in.readInt();
  28.         x = in.readFloat();
  29.         y = in.readFloat();
  30.         return this;
  31.     }
  32. }
  33.  
  34. public class Main{
  35.    
  36.     public static void main(String[] args){
  37.         try {
  38.             DataOutputStream out = new DataOutputStream(new FileOutputStream("test.dat"));
  39.             Test test = new Test("fred", 99, 4.5f, 75.33f);
  40.             test.save(out);
  41.             out.flush();
  42.             out.close();
  43.         } catch (FileNotFoundException e) {
  44.             e.printStackTrace();
  45.         } catch (IOException e) {
  46.             e.printStackTrace();
  47.         }
  48.  
  49.         try {
  50.             DataInputStream in = new DataInputStream(new FileInputStream("test.dat"));
  51.             Test loadedTest = new Test().load(in);
  52.             in.close();
  53.         } catch (FileNotFoundException e) {
  54.             e.printStackTrace();
  55.         } catch (IOException e) {
  56.             e.printStackTrace();
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement