简体   繁体   中英

How to create a .java file using java?

I want to create a .java file but I'm doing something wrong as when I try to create it, I simply get a directory named example.java.

What I want to do is actually create a file with the extension .java

This is the snippet of my code which isn't working as wished:

new File(src, name + ".java").mkdir();

How can I implement as described above?

File is just an abstract representation of your file. Create a new File object won't create it for "real"

You have to call the method createNewFile on it :

File f = new File(src, name + ".java");
if(!f.exists())//check if the file already exists
    f.createNewFile();
new File(src, name + ".java").createNewFile();

Use createNewFile instead of mkdir .

mkdir as the name implies will create a directory.

Creating a new file with the new NIO.2 API (recommended if you're using Java SE 7 or greater):

Path javaFilePath = Paths.get(src, name + ".java");
if (! Files.exists(javaFilePath)){
    Files.createFile(javaFilePath);
}

Tutorial: http://docs.oracle.com/javase/tutorial/essential/io/file.html#creating

Javadoc:

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html

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