Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Wajid Mohammed
Wajid Mohammed
5,698 Points

Java file copy problem using FileWriter class

I am just trying play with FileReader and FileWriter classes to practice Java and wrote the method below to copy the content of a file called poem.txt to a new file poem_new.txt .

Upon calling the method from a separate main class it runs successfully and creates the new file poem_new.txt but doesn't copy the content of poem.txt. In fact, it generates an empty zero byte file.

In order to check wether file reading is correct I used the temporary print statement by removing the commenting and it seems read function is reading the characters fine.

Could some please help me understand where I am wrong?

Thank you.


public void copyFileCharacterWise(){

try{

FileReader fr = new FileReader("./poem.txt");
FileWriter fw = new FileWriter("./poem_new.txt");

 int x = fr.read();

  while(x != -1){
    //System.out.printf("value is %s %n",x);
    fw.write(x);
    x = fr.read();
   }
  }

catch(FileNotFoundException fnfe){ System.out.println("File not found or cannot read write"); } catch(IOException e){ System.out.println("Cannot read or write the file"); } }