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 ();
}
}
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 asall those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as
Double click the
file.txt
, then save it,command + s
, that worked in my case. Also, make sure thefile.txt
is saved in the project folder. If that does not work.The
PrintWriter
class can actually create the file for you.This example works in JDK 1.7+.
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.If you want to use PrintWrite then try this code
throw an exception for the file.