I want to write ONLY the values of the data members of an object into a file, so here I can can't use serialization since it writes a whole lot other information which i don't need. Here's is what I have implemented in two ways. One using byte buffer and other without using it.
Without using ByteBuffer: 1st method
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(); } } } Using byte buffer: One more thing is that the size of the data members will always remain fixed i.e. characterData= 1byte, shortData= 1byte, integerData= 2byte and stringData= 3byte. So the total size of this class is 7byte ALWAYS
2nd method
// 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 I want know which one of the two methods is more optimized? And kindly give the reason also.
The above class DemoSecond is just a sample class.
My original classes will be of size 5 to 50 bytes. I don't think here size might be the issue. But each of my classes is of fixed size like the DemoSecond
Also there are so many files of this type which I am going to write in the binary file.
PS
if I use serialization it also writes the word "characterData", "shortData", "integerData","stringData" also and other information which I don't want to write in the file. What I am corcern here is about THEIR VALUES ONLY. In case of this example its:'c', 7, 3,4'p','e','n'. I want to write only this 7bytes into the file, NOT the other informations which is USELESS to me.
transientall the unnecessary parts?