Erased
Erased

Reputation: 571

WriteBytes write String in my file

Got a little problem than I can't understand. I have a String and I want to write it into byte in a file .txt (for test). Here is my code:

// Check writeVarString, writing in checkVarString.txt to verify 
fos = new FileOutputStream(pathCheckFile + "//checkVarString.txt");
dos = new DataOutputStream(fos);

VarInt.writeVarString("Test number  1 for function writeVarString()", dos);

Here is my function writeVarString():

public static void writeVarString(String value, DataOutput out) throws IOException {
    try {
        int valueLength = value.length();

        if (valueLength > 0) {
            out.writeBytes(value);
        }
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

Ok, it should work. Then I start my app and when I open my test file I got this:

Test number 1 for function writeVarString()

Why I get a readable String? I should got bytes. I already try to use with byte[] array = value.getBytes() then use out.write(array) but got same result.

Upvotes: 0

Views: 748

Answers (3)

KayV
KayV

Reputation: 13855

As specified in the writeBytes documentations:

void java.io.DataOutputStream.writeBytes(String s) throws IOException

Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. If no exception is thrown, the counter written is incremented by the length of s.

Note that it writes " string to the underlying output stream as a sequence of bytes", and every character/integer/short/long is a sequence of bytes( which itself is a sequence of bits). So it is just the basic computer science knowledge.

Upvotes: 0

Gorazd Rebolj
Gorazd Rebolj

Reputation: 825

You are doing it correctly. What's written in the file is bytes. In fact anything you write to a file will always be bytes.

However when you read the file, the application (text editor, cat command etc) will always try to interpret the file as text.

So your sollution is correct, it's just that you can't see the raw bytes as such.

Upvotes: 1

mkysoft
mkysoft

Reputation: 5758

Because every character stored as byte in files. Your text editor read bytes and match them with char using fonts. Also there is encoding mechanism exists for string operation. You can use hex editors or plugin for looking byte/hex represents.

Upvotes: 3

Related Questions