Created
January 7, 2017 14:13
-
-
Save jjhop/d1e8addbd9eca849de0ba3982bd72b90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package imbir; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
import java.util.Date; | |
public class TestC { | |
private final static File outputFile = new File("plik.dat"); | |
public static void main(String[] args) throws Exception { | |
SomeData date = new SomeData(12, "abc", new Date()); | |
saveTofile(outputFile, date); | |
System.out.println("Zapisany."); | |
SomeData restoredData = readFromFile(outputFile); | |
System.out.println(restoredData); | |
} | |
static SomeData readFromFile(File file) throws IOException, ClassNotFoundException { | |
try (ObjectInputStream objectIn = new ObjectInputStream(new FileInputStream(file))) { | |
Object obj = objectIn.readObject(); | |
return (SomeData) obj; | |
} | |
} | |
static void saveTofile(File file, Serializable object) throws IOException { | |
try (ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream(file))) { | |
objectOut.writeObject(object); | |
objectOut.flush(); | |
objectOut.close(); | |
} | |
} | |
} | |
class SomeData implements Serializable { | |
private static final long serialVersionUID = 13423L; | |
final int x; | |
final String napis; | |
final Date data; | |
public SomeData(int x, String napis, Date data) { | |
this.x = x; | |
this.napis = napis; | |
this.data = data; | |
} | |
@Override | |
public String toString() { | |
return "SomeData{" + | |
"x=" + x + | |
", napis='" + napis + '\'' + | |
", data=" + data + | |
'}'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment