java.io.File exists () and current path

When performing a process that automatically creates a file, such as the default constructor of FileWriter, there is a risk of overwriting if the file exists first. So I decided to use exists () in java.io.File.

So the first thing I came up with was

Troublesome example


 public static void main(String[] args){
  /**
  args[0] =Created with FileWriter's default constructor
File name to be written (without extension);
  */

  String filename = args[0] + ".txt";

  //Get current path and create instance
  String path = System.getProperty("user.dir");
  File file = new File(path + "\\" + filename);

  // exists()Judgment by
  boolean flag = file.exists();
  if (flag) {
   System.out.println(filename + "Exists.");

I thought I had to do something like that. This is because there were many examples of writing the current path exactly when investigating how to use exists (). And that's probably correct.

However, since it depends on the contents of the command line input (args [0]) in the first place, the current path including the file name cannot be prepared from the beginning, and as a preparation before creating a file with FileWriter, it is in the current directory. If you only need to check, in fact

A clean example


 public static void main(String[] args){
  String filename = args[0] + ".txt";

  //Create an instance
  File file = new File(filename);

  // exists()Judgment by (same below)
  boolean flag = file.exists();
  if (flag) {
   System.out.println(filename + "Exists.");

This was enough.

So, current path + when searching for the file name you are looking for with exists (), you don't have to put the full path in the File constructor, just the file name will work .

Recommended Posts