Java examples for File Path IO:Serialization
Deserializing an Object
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; public class Main { public void m() { try {/*from w ww .j a v a 2s . c om*/ // Deserialize from a file File file = new File("filename.ser"); ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object javax.swing.JButton button = (javax.swing.JButton) in.readObject(); in.close(); // Get some byte array data byte[] bytes = getBytesFromFile(file); // Deserialize from a byte array in = new ObjectInputStream(new ByteArrayInputStream(bytes)); button = (javax.swing.JButton) in.readObject(); in.close(); } catch (ClassNotFoundException e) { } catch (IOException e) { } } // Returns the contents of the file in a byte array. public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); return bytes; } }