When writing to a binary file like this:
byte[] content = {1,2,3};
FileOutputStream output = new FileOutputStream("data.bin");
DataOutputStream fileName = new DataOutputStream(output);
fileName.writeInt(content.length);
for (int i = 0; i < content.length; i++)
{
fileName.writeInt(content[i]);
System.out.println(content[i]);
}
fileName.close();
When reading it back using FileInputStream/DataInputStream and .readInt() everything is ok.
(If i use .skip(4); because the first one seems to contain a value wich is the number of digits written)
However, if the byte[] content is replaced with input using scanner.
java.util.Scanner in = new java.util.Scanner(System.in);
String inputAsString = in.nextLine();
byte[] content = inputAsString.getBytes();
I noticed it is written to the binaryfile in decimal. 1 becomes 49, 2 is 50, 3 is 51 …
My question is how can i read it back to 1, 2, 3 just like the first example with the hardcoded byte array.
When you read in data from input it’s a string. So you’re getting ascii/utf-x bytes. So the value you’re writing is the byte. You want to turn the input you read into an int:
Note that 51 is ascii value assigned to the character ‘3’
If you write it out as an int you should be able to read it in as such as well.