The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

FileReader.read() reads garbage

Hi,

I have a problem with the FileReader class. I want to read and copy a file and skip certain bytes. However, when I have a FileReader fr and I have it read(), at a very certain point it reads something else entirely, and subsequently writes that garbage into the new file. It only happens with a certain file though. Here is example code and the file in question:

That's really just a fancy way of copying a file byte for byte so I can edit or leave out bytes as they are read.

The problem is this:

The in.txt that I have appended has the value 0x90 at address 0x1E5. However, when I run the above code on in.txt, the out.txt suddenly has the value 0x3F at the same address, and a System.out.print tells me that the read() function has read the nonsense value 0xFFFD at that position!

The same thing happens several times in the file, with different in-values between 0x80 and 0x9D, maybe more, but always replacing the original value with 0x3F in the out file.

It also happens with 1-byte files that contain, for example, the value 0x90 as the only byte. It gets replaced to 0x3f in the out file.

What is the problem here and how can I fix that? Remember that I don't just want to copy the file wholesome, I want to edit/skip certain bytes before writing.

Re: FileReader.read() reads garbage

Take a look at the API for FileReader. In particular note the following line:
"FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream."