3

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.

0

2 Answers 2

1

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:

int toWrite = parseInt(inputAsString);
fileName.writeInt(toWrite);

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Paul! Integer.parseInt(inputAsString);
0

Use in.nextByte() in a loop to read the the entries as byte.

     byte[] bytes = new byte[SIZE];
     int indx = 0;
     while(in.hasNextByte()){
        bytes[indx++] = in.nextByte();
     }

EDIT: If you don't know the size then:

    List<Byte> byteList = new ArrayList<Byte>();
    while(in.hasNextByte()){
       byteList.add(in.nextByte());
    }
    Byte[] bytes = byteList.toArray(new Byte[]{});

3 Comments

Thank you. I guess it is possible to use .length instead of knowing the [SIZE]?
@user1879391: I updated the answer with unknown size reading.
Great! Now i have two solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.