1

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?

3

4 Answers 4

4

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();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3

Use createNewFile instead of mkdir.

mkdir as the name implies will create a directory.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.