3

I want to create a file but the below code doesn't create any file.

package InputOutput; import java.io.*; public class FinalProject{ private File f; public File createFile() throws IOException{ f = new File("E:\\Programming\\Class files\\practice\\src\\InputOutput\\helpSystem.txt"); return f; } public static void main(String[] args) throws IOException{ FinalProject fp = new FinalProject(); fp.createFile(); } } 

4 Answers 4

4

In Java File represents a path name to a file or a directory, not a writable file stream. If you need to create a file, call createNewFile on the File object:

try { f.createNewFile(); } catch (IOException ex) { // Cannot create new file } 
Sign up to request clarification or add additional context in comments.

4 Comments

I tried your code for creating a file. Is it supposed to be "fp.createFile().createNewFile();"?? or something like "fp.createNewFile()"?
@nick-s createNewFile is a method on File. Since your createNewFile method returns a File, you can call createNewFile on it. You could also use f variable that your createFile() method sets. Finally, you could add a call to createNewFile() right in your createFile() method.
@dasblinkenlight I couldn't understand the use of createFile() method called by f variable. I tried using your code but there is compile error while if I just use 'f.createNewFile()' it works fine. Can you tell me the purpose of using createFile() before createNewFile() in ur code?
@nick-s I wanted to keep modifications to your code to the minimum, so I suggested a change fp.createFile(); to fp.createFile().createNewFile();. However, it does not matter from where you call createNewFile(): that was the only part missing from your code, which was otherwise correct.
2

Add the following in your createFile method:

if(!f.exists()) { f.createNewFile(); } 

1 Comment

createNewFile() "..creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist." (The if check is redundant.)
2

This is the correct code to create the file.

public File createFile() throws IOException{ f = new File("E:\\Programming\\Class files\\practice\\src\\InputOutput\\helpSystem.txt"); if(!f.exists()) { f.createNewFile(); } return f; } 

Comments

0

Call the createNewFile method which creates a new file if the specified file not exists Here is the link to the instructions.

Hope it helped!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.