实现代码
- 通过ObjectOutputStream类的writeObject函数可以直接向二进制文件中写入类对象
- 这种方式得到的二进制文件会比文本文件更大,可能是二进制文件中含有类对象的其他信息
- 类对象需要实现Serializable接口,接口中没有需要实现的函数
测试的类
class TestDataStruct implements Serializable{
String name;
public TestDataStruct(String name,double x,double y,double z,String atr1,String atr2){
this.name = name;
this.x = x;
this.y = y;
this.z = z;
this.atr1 = atr1;
this.atr2 = atr2;
}
}
文本文件
F1,8251.409,8252.466,38.477,val1,vall1
F2,8252.129,8251.382,38.46,val2,vall2
F3,8254.335,8250.181,38.443,val3,vall3
F4,8256.815,8249.749,38.433,val4,vall4
F5,8253.534,8253.266,38.395,val5,vall5
F6,8253.058,8255.03,38.157,val6,vall6
F7,8255.883,8251.085,38.401,val7,vall7
F8,8252.952,8252.742,38.403,val8,vall8
F9,8250.394,8255.645,38.461,val9,vall9
写入代码与读取代码
/**写入二进制文件
*从文本文件中读入数据,写入到二进制文件中
*/
static void readClass2File() throws IOException {
ObjectOutputStream objectOutputStream= new ObjectOutputStream(
new FileOutputStream(new File("/home/fly/桌面/hadoopPrj/tempBinary")));
Scanner in = new Scanner(new File("/home/fly/桌面/hadoopPrj/data/testData.csv"));
String str;
String strs[];
TestDataStruct testDataStruct;
while (in.hasNextLine()) {
str = in.nextLine();
strs = str.split(",");
testDataStruct = new TestDataStruct(strs[0], Double.valueOf(strs[1]),
Double.valueOf(strs[2]),Double.valueOf(strs[3]),strs[4],strs[5]);
objectOutputStream.writeObject(testDataStruct);
static void readFile2Class() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("/home/fly/桌面/hadoopPrj/tempBinary")));
TestDataStruct testDataStruct;
testDataStruct = (TestDataStruct)objectInputStream.readObject();
try {
while (testDataStruct != null) {
System.out.println(testDataStruct.name);
System.out.println(testDataStruct.z);
testDataStruct = (TestDataStruct) objectInputStream.readObject();
}
} catch (EOFException e) {
} finally {
objectInputStream.close();
}
}
}
}