2

Is there a way to use the File class to create a new text file? After doing some research, I tried:

import java.io.*;

public class createNewFile
{
    public static void main(String args[]) throws IOException
    {
        File file = new File("newfile.txt");
        boolean b1 = file.createNewFile();
    }
}

...but there is still no newfile.txt in my source directory. It would also seem like there would be a void method to do this, instead of having to result to a boolean. Is there a way to do what I'm trying to do with the FIle class, or so I have to result to another class?

4
  • stackoverflow.com/questions/2885173/… hope it helps Commented Oct 7, 2015 at 6:08
  • Rustam: It's false. Kumar Saurabh: Thanks for the link. I actually ran across that in my searches, but was wondering if I could do it with the File class since that's what I was taught on as far as reading from files goes. Commented Oct 7, 2015 at 6:15
  • That means either file already exist or not created. try printing file.getAbsolutePath() Commented Oct 7, 2015 at 6:19
  • Thanks. Turns out wero hit the nail on the head. The file was created in the current working directory, not exactly in the folder where I was looking. I guess I'm good now! :) Commented Oct 7, 2015 at 6:23

2 Answers 2

3

You have created a file but apparently not in your source directory but in the current working directory. You can find the location of this new file with:

 System.out.println(file.getAbsolutePath());

One possibility to control the location of the new file is to use an absolute path:

 File file = new File("<path to the source dir>/newfile.txt");
 file.createNewFile();
Sign up to request clarification or add additional context in comments.

Comments

0

You can try like this:

File f = new File("C:/Path/SubPath/newfile.txt");
f.getParentFile().mkdirs();
f.createNewFile();

Also make sure that the path where you are checking and creating the file exists.

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.