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:
import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class Trunc { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String in = "in.txt"; String out = "out.txt"; File inFile = new File(in); File outFile = new File(out); FileReader fr = new FileReader(inFile); FileWriter fw = new FileWriter(outFile); while(fr.ready()) { int temp = fr.read(); fw.write(temp); } fr.close(); fw.close(); } }
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.