Mutating Algorithm
Mutating Algorithm

Reputation: 2758

Copying a file character by character in Java

I'm working on an exercise where I must copy a file character by character in Java. I am working with the following file:

Hamlet.txt
To be, or not to be: that is the question.
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them ?

I create second file, called copy.txt which will contain a character by character copy of Hamlet.txt The problem is that after I run my code, copy.txt remains empty.

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class Combinations {
    public void run() {
        try {
            BufferedReader rd = new BufferedReader(new FileReader("Hamlet.txt"));
        PrintWriter wr = new PrintWriter(new BufferedWriter(new FileWriter("copy.txt")));
        copyFileCharByChar(rd, wr);
    }catch(IOException ex) {
        throw new RuntimeException(ex.toString());
    }
}

private void copyFileCharByChar(BufferedReader rd, PrintWriter wr) {
    try {
        while(true) {
            int ch = rd.read();
            if(ch == - 1) break;
            wr.print(ch);
        }
      } catch(IOException ex) {
        throw new RuntimeException(ex.toString());
    }
    }

public static void main(String[] args) {
    new Combinations().run();
}
}

So I write a method copyFileCharByChar that takes in a BufferedReader object rd and a FileWriter object wr. rd reads each individual character and the wr writes that corresponding character. What am I doing wrong here ?

Upvotes: 1

Views: 1387

Answers (1)

martinez314
martinez314

Reputation: 12332

You need to cast print in this case:

wr.print((char)ch);

or use the write method:

wr.write(ch);

You also need to close your PrintWriter:

wr.close();

Upvotes: 3

Related Questions