0

Anyone have any idea why below code doesnt create a new file in the C: directory ?

public class FirstFileProgram {

import java.io.* ;

    public static void main(String[] args) {
       File f=new File("C:\\text.txt");

        System.out.println(f.getName());
        System.out.println(f.exists());
    }
  • 1
    Possible duplicate of [How to create a file in a directory in java?](http://stackoverflow.com/questions/6142901/how-to-create-a-file-in-a-directory-in-java) – NineBerry Feb 21 '16 at 18:02
  • 1
    This is 2016. `File` is deprecated. Use `Path` and (java.io.)`Files` instead. – fge Feb 21 '16 at 18:04

2 Answers2

0

You have created an object which is linked to C:\text.txt file, but not actually created a file. You need use createNewFile() to create a file using object of file class i.e. f. See below:

public class FirstFileProgram { public static void main(String[] args) {

  File f = null;
  boolean bool = false;

  try {
     // create new file
     f = new File("test.txt");

     // tries to create new file in the system
     bool = f.createNewFile();

     // prints
     System.out.println("File created: "+bool);

     // deletes file from the system
     f.delete();

     // delete() is invoked
     System.out.println("delete() method is invoked");

     // tries to create new file in the system
     bool = f.createNewFile();

     // print
     System.out.println("File created: "+bool);

  }catch(Exception e){
     e.printStackTrace();
      }
   }
}
Alok Gupta
  • 1,353
  • 1
  • 13
  • 29
0

@Alok Gupta Answer is Ok. Just incase you are using Java 7 or later you may use

public class CreateFileUsingJava {

     public static void main(String[] args) throws IOException {
        Path path = Paths.get("C:\\test.txt");
        try {
            Files.createFile(path);
        } catch (FileAlreadyExistsException e) {
            System.err.println("File exists: " + e.getMessage());
        }
     }
 }
Norrey Okumu
  • 21
  • 1
  • 4