how to use printwriter to create and write to a file

Brandon Nolan picture Brandon Nolan · Aug 14, 2014 · Viewed 29.5k times · Source

I am trying to create a new file and print data to said file using the printwriter class.

My code looks like this

File Fileright = new File("C:\\GamesnewOrder.txt"); 

PrintWriter pw = new PrintWriter(Fileright);

for(int i =0;i<=Games2.length-1;i++)
{
    pw.println(Games2[i]);

}

pw.close();

I do have the main method with a throwsIOException.

The error java.iofilenotfound exception keeps appearing at the line where I am creating the printwriter. So is the printwriter not creating the file?

Answer

novice picture novice · Aug 14, 2014

the code works for me.

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.PrintWriter;

  public class NewClass {

     void n() throws FileNotFoundException {
             File Fileright = new File("/home/ubuntu/Documents/f.txt");

             PrintWriter pw = new PrintWriter(Fileright);

             for (int i = 0; i <= 3; i++) {
                pw.println(i);
                System.out.println(i);

             }

             pw.close();
      }

      public static void main(String[] args) throws FileNotFoundException {

             new NewClass().n();
      }

}

output:(in file: /home/ubuntu/Documents/f.txt)

0
1
2
3