Search code examples
javaprocessingprintwriter

PrintWriter throwing FileNotFoundException


I am writing a code that outputs to a text file using the PrintWriter class. However, when I try to initialize a new PrintWriter it throws a FileNotFound exception.

Here are two versions of my code that both don't work, writer is initialized in the global variable as a PrintWriter.

File file = new File(fileName);
writer = new PrintWriter(fileName);
writer.println("N: " + N);
writer.println("E: " + E);
writer.println("D: " + D);
writer.flush();
writer.close();

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

writer = new PrintWriter(fileName);
writer.println("N: " + N);
writer.println("E: " + E);
writer.println("D: " + D);
writer.flush();
writer.close();

Here is a list of the imports I'm using, am I possibly missing one?

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.math.*;
import java.math.BigInteger;
import java.util.*;
import java.io.*;

Solution

  • Both the code seems to be correct and working fine for me. Ensure that the path is given properly. If in case no path given ensure to call the method createNewFile to create the file from abstract filename as below

    File file = new File("test1.txt");
    file.createNewFile();
    
    PrintWriter writer = new PrintWriter("test1.txt");
    writer.println("N: ");
    writer.println("E: ");
    writer.println("D: ");
    writer.flush();
    writer.close();
    

    You can also use file object along with PrintWriter.