【发布时间】:2014-07-09 05:52:57
【问题描述】:
我想ONLY将对象的数据成员的值写入文件,所以这里我不能使用序列化,因为它写了很多我不需要的其他信息。这是我以两种方式实现的。一个使用字节缓冲区,另一个不使用它。
不使用 ByteBuffer: 第一种方法
public class DemoSecond {
byte characterData;
byte shortData;
byte[] integerData;
byte[] stringData;
public DemoSecond(byte characterData, byte shortData, byte[] integerData,
byte[] stringData) {
super();
this.characterData = characterData;
this.shortData = shortData;
this.integerData = integerData;
this.stringData = stringData;
}
public static void main(String[] args) {
DemoSecond dClass= new DemoSecond((byte)'c', (byte)0x7, new byte[]{3,4},
new byte[]{(byte)'p',(byte)'e',(byte)'n'});
File checking= new File("c:/objectByteArray.dat");
try {
if (!checking.exists()) {
checking.createNewFile();
}
// POINT A
FileOutputStream bo = new FileOutputStream(checking);
bo.write(dClass.characterData);
bo.write(dClass.shortData);
bo.write(dClass.integerData);
bo.write(dClass.stringData);
// POINT B
bo.close();
} catch (FileNotFoundException e) {
System.out.println("FNF");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE");
e.printStackTrace();
}
}
}
使用字节缓冲区:还有一件事是数据成员的大小将始终保持固定,即 characterData= 1byte、shortData= 1byte、integerData= 2byte 和 stringData= 3byte。所以这个类的总大小是 7byte ALWAYS
第二种方法
// POINT A
FileOutputStream bo = new FileOutputStream(checking);
ByteBuffer buff= ByteBuffer.allocate(7);
buff.put(dClass.characterData);
buff.put(dClass.shortData);
buff.put(dClass.integerData);
buff.put(dClass.stringData);
bo.write(buff.array());
// POINT B
我想知道这两种方法中哪一种更优化?并请说明原因。
上面的类DemoSecond只是一个示例类。
我的原始类将是大小为 5 到 50 个字节。我不认为这里的大小可能是问题。 但是我的每个班级都是固定大小的,例如 DemoSecond
还有很多这种类型的文件,我要写入二进制文件。
附言
如果我使用序列化,它还会写入单词“characterData”、“shortData”、“integerData”、“stringData”以及我不想在文件中写入的其他信息。我在这里担心的是仅限他们的价值观。在这个例子中是:'c', 7, 3,4'p','e','n'。我只想将这 7 个字节写入文件,而不是其他对我无用的信息。
【问题讨论】:
-
为什么不声明
transient所有不必要的部分? -
如果我使用序列化,它也会写入单词“characterData”、“shortData”、“integerData”、“stringData”。我在这里担心的只是价值观。在本例中:'c', 7, 3,4'p','e','n'
-
你为什么不在你的代码中加入一些计时,并用一百万个对象来测试它。我的猜测是非缓冲输出流是最快的。
标签: java java-io bytebuffer