简体   繁体   中英

File not created in Java (Eclipse)

So I've been doing like the simplest thing ever. Create a text file for a Java application. Just directly in the C directory:

File file = new File("C://function.txt");
System.out.println(file.exists());

The file never shows up though, I changed the slashes, changed the path, nothing. Could anyone help me out here?

There are many methods to create a new file with java : (You should firstly verify the permission to create a file in that folder c: )

  1.   String path = "C:"+File.separator"function.txt"; File f = new File(path); f.mkdirs(); f.createNewFile(); 

    __ or

      try { //What ever the file path is. File f = new File("C:/function.txt"); FileOutputStream is = new FileOutputStream(f); OutputStreamWriter osw = new OutputStreamWriter(is); Writer w = new BufferedWriter(osw); w.write("Line 1!!"); w.close(); } catch (IOException e) { System.err.println("Problem writing to the file function.txt"); } 

After Java 7, you should use the new I/O API instead of the File class to create new files.

Here is an example:

Path path = Paths.get("C://function.txt");
try {
    Files.createFile(path);
    System.out.println(Files.exists(path));
} catch (IOException e) {
    e.printStackTrace();
}

You are just creating a File object, not a file itself. So in-order to create new file you need use below command:

file .createNewFile();

This would create your file under C:\\ drive. Maybe you can also check if it is already exsits and handle exception etc.

If the file is not exist you can create a new file like:

if(!file.exists()) {
        try {
            file.createNewFile();
            System.out.println("Created a new File");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

The simplest way to do this:

 String path = "C:"+File.separator+"function.txt";

 File file = new File(path);
 System.out.println(file.exists());

try this:

File file = new File("C://function.txt");
if (!file.isFile())
    file.createNewFile();

Try this

File file = new File("C:/test.text");
f.createNewFile();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM