1

My problem is when I get the data from a text file it seems to be in the wrong encoding or somthing. I dont know how to get around this issue sorry. Thanks in advance. Here is the code.

private static String readLogFile(String path, File f) throws IOException {
    if (f.exists()){
    String data;
        try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {
            char ch = raf.readChar();
            raf.seek(f.length());
            String dataCh = String.valueOf(ch);
            data = dataCh.toString();
            System.out.println(data);
        }
        return data;
    }

    else{
        String data = "";
        return data;
    }
}
2
  • Why the seek to EOF? Why are you calling toString() on a String? Why aren't you closing the file? WHy are you using a RandomAccessFile at all when you are just reading the start of it? Commented Aug 29, 2012 at 5:18
  • I have dumped this code as it had to many errors and now i am using FileInputStream . But yes the code about is terrible. Commented Aug 29, 2012 at 6:53

1 Answer 1

1

From the Java Docs

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Note, "two bytes are read"

Because Java supports Unicode character's the stream is automatically assuming that reading a character from the stream needs to produce a Unicode character.

Try char ch = (char)raf.readByte(); instead

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

Comments

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.