I need to write a string in a file as bytes in UTF-8 and then get these bytes back from file and convert it back to string and as a consiquence get the same string. May be it sounds easy but there is a hidden problem such as incorrect symbols in file. I mean that after appending in file it must contain something like:
00000008 d0bad0bb d18ed187 00000010 etc...
But it contains stuff like that:
mystring ---a lot of space--- (and the symbol that doesn't display here)
So, what have I already done? I've tried this way:
Before code read this: I keep strings in HashMap < String, String > that's why my code contains get(...) etc.
try {
FileOutputStream oStream = new FileOutputStream("filename.txt");
Set<String> keySet = storage.keySet();
ByteBuffer buffer = ByteBuffer.allocate(1024);
for (String key : keySet) {
byte[] keyInByte = key.getBytes("UTF-8");
byte[] valueInByte = storage.get(key).getBytes("UTF-8");
oStream.write(buffer.putInt(0, valueInByte.length).array());
oStream.write(keyInByte);
oStream.write((buffer.putInt(0, valueInByte.length).array()));
oStream.write(valueInByte);
}
} catch (Exception e) {
System.err.println("permission denied");
}
I have also tried use PrintWriter, FileWriter, etc... but it doesn't give what I need. For example, some of them need toString() method but after toString() I will lose the ability to work with bytes.
! Notice, that I've tried to change my notepad to UTF-8 encode, but it gives no result.
.txtmeans text not binary. BTW DataInput/OuputStream as a writeUTF/readUTF method which does something like this more efficiently.