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?

NickH88
  • 93
  • 2
  • 9
  • http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java hope it helps – Kumar Saurabh Oct 07 '15 at 06: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. – NickH88 Oct 07 '15 at 06:15
  • That means either file already exist or not created. try printing `file.getAbsolutePath()` – Rustam Oct 07 '15 at 06: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! :) – NickH88 Oct 07 '15 at 06:23

2 Answers2

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();
wero
  • 32,544
  • 3
  • 59
  • 84
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.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331