How to use printwriter to create and write to a file

I am trying to create a new file and print data in the specified 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 have a main method with throwsIOException

.

The error java.iofilenotfound

keeps popping up on the line where I am creating the printwriter. So the printer doesn't create the file?

+3


source to share


2 answers


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

+3


source


FileNotFoundException - if the given file object does not denote an existing, rewritable regular file and a new regular file with that name cannot be created or if some other error occurs when opening or creating a file



Please check the "Enable" file that you can use canRead()

, canWrite()

to check it out, but this may not be enough.

+2


source







All Articles