File creation

In this chapter you will learn:

  1. How to create a physical file on disk
  2. How to create a temporary file
  3. How to create a temporary file with the directory you passed in

Create a file

We can create a file once we have a File object. We can also choose to create file or a temp file.

  • boolean createNewFile()
    creates a new file.
  • static File createTempFile(String prefix, String suffix)
    creates a file in default temporary-file directory with prefix and suffix.
  • static File createTempFile(String prefix, String suffix, File directory)
    creates a file in the specified directory with prefix and suffix.
import java.io.File;
import java.io.IOException;
/*from   j a v a 2 s  .  c  o  m*/
public class Main {

  public static void main(String[] args) {

    File aFile = new File("c:/aFolder");
    
    try {
      System.out.println(aFile.createNewFile());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Create a temporary file

The following code creates a temporary file under user's home directory.

import java.io.File;
import java.io.IOException;
//  j a  va  2  s.co m
public class Main {

  public static void main(String[] args) {

    
    try {
      File tempFile = File.createTempFile("abc","txt");
      System.out.println(tempFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

create a temporary file with a directory

The code below creates a temporary file with the directory you passed in:

import java.io.File;
import java.io.IOException;
/*java2 s  .c om*/
public class Main {

  public static void main(String[] args) {

    
    try {
      File tempFile = File.createTempFile("abc","txt",new File("c:\\"));
      System.out.println(tempFile);//
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to test whether this abstract pathname is absolute
  2. How to get file path and name