59

I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.

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

public class Testing {

  public static void main(String[] args) {

    File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
    PrintWriter printWriter = new PrintWriter ("file.txt");
    printWriter.println ("hello");
    printWriter.close ();       
  }
}
user unknown
  • 35,537
  • 11
  • 75
  • 121
SPARK
  • 595
  • 1
  • 4
  • 5

11 Answers11

77

If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.

As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see

FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

You should try creating a path for the folder it contains before:

File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();

PrintWriter printWriter = new PrintWriter(file);
Jack
  • 131,802
  • 30
  • 241
  • 343
  • Suppose I ll give `File file = new File("dir1/dir2/directory/file.txt");` then where it will create directory ? inside application or outside ? – Java Curious ღ Dec 11 '13 at 11:46
  • 1
    @JavaCuriousღ: allocating a File instance doesn't create anything. The `File` class is just a placeholder for a file which can also not exists at all. You should use `mkDirs()` to create the directories, as explained in my answer. – Jack Dec 11 '13 at 14:54
  • Yes That I know, I just miss to write code for mkdirs but if I ll use this one then where will this dir will create ? Inside app or outside and if inside then what to do id i want to create it outside the app ? – Java Curious ღ Dec 12 '13 at 05:20
  • @JavaCuriousღ This will create the physical directory in the operating system instead of just being a File object in the heap. – Ciphor Dec 12 '13 at 10:22
  • @Ciphor - Yes that I know that it will create physical directory but where that I am asking. In Web App or outside the app. ? – Java Curious ღ Dec 12 '13 at 10:54
12
import java.io.PrintWriter;
import java.io.File;

public class Testing {

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

    File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
    PrintWriter printWriter = new PrintWriter ("file.txt");
    printWriter.println ("hello");
    printWriter.close ();       
  }
}

throw an exception for the file.

JeanGray
  • 121
  • 1
  • 2
5

Pass the File object to the constructor PrintWriter(File file):

PrintWriter printWriter = new PrintWriter(file);
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
4
import java.io.File;
import java.io.PrintWriter;

public class Testing 
{
    public static void main(String[] args) 
    {

        File file = new File("C:/Users/Me/Desktop/directory/file.txt");

        PrintWriter printWriter = null;

        try
        {
            printWriter = new PrintWriter(file);
            printWriter.println("hello");
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if ( printWriter != null ) 
            {
                printWriter.close();
            }
        }
    }
}
Stradivariuz
  • 2,523
  • 1
  • 18
  • 6
  • 1
    This will throw NPE if `FileNotFoundException` is thrown. You should use `if(printWriter != null) printWriter.close();` – Eng.Fouad Jul 16 '12 at 00:18
1

Java doesn't normally accept "/" to use in defining a file directory, so try this:

 File file = new File ("C:\\Users\\user\\workspace\\FileTester\\myFile.txt");

If the file doesn't exist do:

 try {
      file.createNewFile();
 }
 catch (IOException e) {
 e.printStackTrace();
 }
MBJH
  • 1,571
  • 3
  • 17
  • 36
Galen Nare
  • 336
  • 1
  • 2
  • 9
1

You should have a clear idea of exceptions in java. In java there are checked exceptions and unchecked exceptions.

Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.

NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:

CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.

How to resolve: 1.Put your code in try catch block:

2.use throws keyword as shown by other guys above.

Advice:Read more about Exceptions.(I personally love this topic)

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
0

Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException ) and then also use full path of file in which you are writing as

PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");

all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as

import java.io.*;
public class PrintWriterClass {

public static void main(String arg[]) throws IOException{
    PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
    pw.println("hiiiiiii");
    pw.close();
}   

}
ThePCWizard
  • 3,338
  • 2
  • 21
  • 32
0
import java.io.*;

public class test{
    public static void main(Strings []args){

       PrintWriter pw = new PrintWriter(new file("C:/Users/Me/Desktop/directory/file.txt"));

       pw.println("hello");
       pw.close
    }

}

0

The PrintWriter class can actually create the file for you.

This example works in JDK 1.7+.

// This will create the file.txt in your working directory.

PrintWriter printWriter = null;

try {

    printWriter = new PrintWriter("file.txt", "UTF-8");
    // The second parameter determines the encoding. It can be
    // any valid encoding, but I used UTF-8 as an example.

} catch (FileNotFoundException | UnsupportedEncodingException error) {
    error.printStackTrace();
}

printWriter.println("Write whatever you like in your file.txt");

// Make sure to close the printWriter object otherwise nothing
// will be written to your file.txt and it will be blank.
printWriter.close();

For a list of valid encodings, see the documentation.

Alternatively, you can just pass the file path to the PrintWriter class without declaring the encoding.

Zenohm
  • 548
  • 6
  • 17
Badr DRAIFI
  • 335
  • 4
  • 12
0

Double click the file.txt, then save it, command + s, that worked in my case. Also, make sure the file.txt is saved in the project folder. If that does not work.

PrintWriter pw = new PrintWriter(new File("file.txt"));
pw.println("hello world"); // to test if it works.
David Lee
  • 2,040
  • 17
  • 36
0

If you want to use PrintWrite then try this code

public class PrintWriter {
    public static void main(String[] args) throws IOException {

        java.io.PrintWriter pw=new java.io.PrintWriter("file.txt");
        pw.println("hello world");
        pw.flush();
        pw.close();

    }

}
Navneet Krishna
  • 5,009
  • 5
  • 25
  • 44