Запись и чтение объекта из файла
//Запись и чтение объекта из файла //Объект преобразуется в массив байтов //Из файла считывается массив байтов и преобразуется в объект package readwrite;
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Vector;
public class writeObject {
static void writeObject(String filename, Object obj) throws IOException{ try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream(filename)); out.writeObject(obj); out.close(); //Создание массива байтов ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(obj); out.close(); byte[] buf = bos.toByteArray(); } catch (IOException e) { } } public static byte[] getBytesFromFile(File file) throws IOException, FileNotFoundException { InputStream instr = new FileInputStream(file); // Размер файла long flength = file.length(); if (flength > Integer.MAX_VALUE) { // Слишком большой файл } byte[] bytes = new byte[(int)flength]; int offset = 0; int numberRead = 0; while (offset < bytes.length && (numberRead=instr.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numberRead; } //Все байты считаны? if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } instr.close(); return bytes; } static Object readVector(String filename, Object obj){ Vector res=new Vector(); try { File file = new File(filename); ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); res=(Vector)in.readObject(); in.close(); byte[] bytes = getBytesFromFile(file); in = new ObjectInputStream(new ByteArrayInputStream(bytes)); res=(Vector)in.readObject(); in.close(); } catch (ClassNotFoundException e) { } catch (IOException e) { }
return res; } public static void main(String[] args) throws IOException { Vector vect=new Vector(); vect.add("a"); vect.add("a1"); writeObject("/MyDir/vect.ser", vect); Object obj=new Object(); Object obj1=new Object(); obj1= readVector("/MyDir/vect.ser", obj); vect=(Vector)obj1; System.out.println(vect.get(1)); }
}
05.01.2009
|