Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "new File()" does not create file

Tags:

java

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.

like image 673
CodeGeass Avatar asked Jun 13 '17 13:06

CodeGeass


People also ask

Does new file in Java create file?

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.

Why is file not created in 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).

How do you create a new file in Java?

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.

What is new file () in Java?

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.


2 Answers

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.

like image 190
Mike Nakis Avatar answered Nov 15 '22 11:11

Mike Nakis


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.

like image 30
cris22tian Avatar answered Nov 15 '22 11:11

cris22tian