Question

Edited: Actual mistake was that File1 contents are completely copied into File2 + with some other lines of text. The file was huge. So the question has to be rephrased accordingly. But, the answer is correct. It solves the problem. Extra lines are removed.

Code Snippet:

 public class ReadAFile {
    public static void main(String[] args) throws IOException {
        File file = new File("primes.txt");
        FileReader reader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(reader);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File("primesFile.txt")));
        char[] buffer = new char[1024];
        int read;
        while ((read = bufferedReader.read(buffer)) > 0) {
            writer.write(buffer, 0, buffer.length);
        }
        writer.close();
        bufferedReader.close();
    }
}
Était-ce utile?

La solution

    while ((read = bufferedReader.read(buffer)) > 0) {
        writer.write(buffer, 0, buffer.length);
    }

Usual mistake. You're assuming that read() fills the buffer. Se the Javadoc. You need to use the read count in the write method:

    while ((read = bufferedReader.read(buffer)) > 0) {
        writer.write(buffer, 0, read);
    }

But unless you know for sure that the file is text you should be using streams, not readers and writers.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top