Java How to write a string in file as bytes and get string back -
Java How to write a string in file as bytes and get string back -
i need write string in file bytes in utf-8 , these bytes file , convert string , consiquence same string. may sounds easy there hidden problem such wrong symbols in file. mean after appending in file must contain like:
00000008 d0bad0bb d18ed187 00000010 etc...
but contains stuff that:
mystring ---a lot of space--- (and symbol doesn't display here)
so, have done? i've tried way:
before code read this: maintain strings in hashmap < string, string > that's why code contains get(...) etc.
try { fileoutputstream ostream = new fileoutputstream("filename.txt"); set<string> keyset = storage.keyset(); bytebuffer buffer = bytebuffer.allocate(1024); (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); } } grab (exception e) { system.err.println("permission denied"); }
i have tried utilize printwriter, filewriter, etc... doesn't give need. example, of them need tostring() method after tostring() lose ability work bytes.
! notice, i've tried alter notepad utf-8 encode, gives no result.
if want utilize properties can this.
new properties(map).save(new fileoutputstream("filename.proeprties"));
to load properties
properties prop = new properties(); prop.load(new fileinputstream("filename.properties")); map.putall(prop);
to save copying info can utilize properties map.
key1=value1 key2=value2
note: key cannot contain =
or newline.
this how in binary format
dataoutputstream dos = new bufferedoutputstream(new fileoutputstream("filename.dat"))); dos.writeint(map.size()); (map.entry<string, string> entry : map.entryset()) { dos.writeutf(entry.getkey()); dos.writeutf(entry.getvalue()); } dos.close();
this how write in text, using utf-8
printwriter pw = new printwriter(new outputstreamwriter(new fileouputstream("filename.txt") "utf-8")); pw.println(map.size()); (map.entry<string, string> entry : map.entryset()) { pw.println(encode(entry.getkey())); pw.println(encode(entry.getvalue())); } pw.close(); public static string encode(string s) { // if can assume no new lines, don't anything. homecoming s.replaceall("\\\\", "\\\\\\\\").replaceall("\n", "\\\\n"); }
this produce like
key1 value1 key2 value2
this can edit easy. if youc assume key doesn't have =
or :
or tab, can utilize 1 line properties file
java string file utf-8
Comments
Post a Comment