How to convert string back to bytes in order to write to file in Java?

大兔子大兔子 提交于 2021-01-29 04:04:14

问题


I have a text file that contains the word "cool" in it. I read all the bytes in this file and turn it into a string. However, In another function where I am trying to turn the same string back to bytes to write into the file I don't get what I expected.

Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);

String x = new String();
for(byte b: data){
    x += Byte.toString(b);
}  
System.out.println(x);

Output: "cool" turned into bytes

99111111108

Unfortunately the code below does not write "cool" back to the file, instead it writes 99111111108.

str = "99111111108";
FileOutputStream C = new FileOutputStream("new.txt");
C.write(str.getBytes());
C.close();   

回答1:


Check this out: https://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#toString(byte)

toString

public static String toString(byte b)

Returns a new String object representing the specified byte. The radix is assumed to be 10.

Parameters: b - the byte to be converted Returns: the string representation of the specified byte

See Also: Integer.toString(int)

The issue is that you're turning the string into bytes, but then you're going and turning that byte into a string/character (interpreted as a base 10 number - radix=10) which means you essentially get the ascii equivalent of each character (c=99, o=111, o=111, l=108) which is a number in base 10. However you're the numeric character for each digit. When you go to turn the string back into a byte you're getting the byte for the numeric character not the byte for the letter like you want.

Depending on what you're actually after, you're going to need to find a different approach. It's not clear what you are trying to show by converting to bytes, but if you really want to convert to and from a bitstring (a string composed of the numeric characters for 0s and 1s) you'll have to do more work.

If you delimited the string you're building with some other character like a comma (e.g. 99,111,111,108) then you could assume the delimited substrings were integers (for regular ascii) and pass them to 'Integer.parseInt(s)' or 'Integer.valueOf(s)' and then do a conversion to char and then build the chars into a string.

For example:

StringBuilder sb = new StringBuilder();

String str = "99,111,111,108"; // result of initial conversion
String[] sa = str.split(",");

char ch = '';

for(String s : sa) {
   ch = Integer.parseInt(s);
   sb.append(ch);
}

FileOutputStream fos = new FileOutputStream("new.txt");

fos.write(sb.toString().getBytes());
fos.close();

An important note here is that, for Java at least, chars are just integers except that they a char is interpreted as being an ascii character.

The basic dilemma is, I believe, that converting the bytes to strings is a destructive operation where the context is lost. I.e. the computer no longer knows anything about the original bytes, only what the newly generated string is. Bytes are binary data, but strings are a group of characters (generally ascii, but also UTF of various kinds).




回答2:


Cannot be done. The problem is that in the string "99111111108" the demarcations of where a byte starts and ends are not included. In other words, in this string is "9" the first character, or "99"?




回答3:


If you had the byte values represented as strings, you can convert them back to bytes with the method Byte.valueOf.

byte b = getByte();
String byteAsString = Byte.toString(b); 
System.out.println(byteAsString); //might print something like '111'

byte o = Byte.valueOf(byteAsString);
assertEquals(b,o); //true

To me though it seems like it would be better to just read the data into a String directly with

new String(byteArray, encoding); 

like dnault suggested. With any string you get a character with

"string".charAt(index);

Also it's possible in your loop to get a character directly by casting byte to char. You could do this

for(byte b: data){
    x += (char)b;
}
System.out.println(x);

And this code would print "cool" given the example input you provided, although this is a very naive approach and you would run into trouble when using characters with values larger than byte's max value.



来源:https://stackoverflow.com/questions/36583552/how-to-convert-string-back-to-bytes-in-order-to-write-to-file-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!