File creation

I want to create a file, but the code below does not 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();
    }
}
+3
source share
4 answers

In Java, it Fileis the path to a file or directory, not a writeable file. If you need to create a file, call createNewFilein the object File:

try {
    f.createNewFile();
} catch (IOException ex) {
    // Cannot create new file
}
+4
source

Add the following to your createFile method:

if(!f.exists()) {
    f.createNewFile();
}
+2
source

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;
}
+2
source

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

Hope this helps!

0
source

All Articles