This will be a really dumb question, but i can't seem to create a new file in java to save my life.
It always throws
java.io.FileNotFoundException: Users/username/Documents/testProject/test.txt (No such file or directory)
I have tried like this:
File newFile = new File("Users/username/Documents/testProject/test.txt");
and tried this:
File newFile = new File("/Users/username/Documents/testProject/test.txt");
What am i doing wrong?
Edit: apparently the issue wasn't there. I was trying to read from an empty file later on in the code, sorry folks.
File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java. File createNewFile() method returns true if new file is created and false if file already exists. This method also throws java.
If a file or directory of pathName does not exist, constructing a File object will not create it. Above is a program that constructs a File object and uses one of its methods. The constructor argument is a simple file name (which is also a relative path name).
java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.
createNewFile() is a method of File class which belongs to a java.io package. It does not accept any argument. The method automatically creates a new, empty file. The method returns a boolean value: true, if the file created successfully.
new File("...")
does not create a new file. It creates a new object (in memory) containing a filename. You can then perform operations like exists()
, canRead()
and isDirectory()
on it, and you can invoke createNewFile()
to create an actual file out of it.
Additionally to Mike's answer you will probably need to put double // rather than just a single / as it is used as an escaping sequence. I am not sure if this applies in every situation but in case you still get any errors try this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With