简体   繁体   中英

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM