In this section we will discuss about how to construct file path in Java.
Java Construct File Path
In this section we will discuss about how to construct file path in Java.
A file path can be constructed manually or by a Java program. It is best practice to construct a file path in Java by a Java Program. When you will construct a file path manually the path name will be system dependent because the file separator character is system dependent. For example : Windows uses '\' (separator character) and UNIX uses '/' (separator character). But, we can construct a file path system independent due to separator and separatorChar. These are public static fields of the java.io.File class. So, when such fields are used to construct a file path it separates the path name by the separator what the underlying system uses to separate the file path name.
Example
An example given below demonstrates that how to construct a file pathname by a Java program in Java. In this example I have created a Java class where I have write the code for command line input and then get the user's current working directory and uses the File.separator to apply the separator character in constructing of file pathname. Then used createNewFile() method to create a new file with the specified name in the specified directory. In this example a file name can be given at the time of execution of the class i.e. file name can be given through command line.
Source Code
JavaConstructFilePathnameExample.java
import java.io.File; import java.io.IOException; public class JavaConstructFilePathnameExample { public static void main(String args[]) { String f = args[0]; String currDir = System.getProperty("user.dir"); System.out.println("\n Current Working Directory = "+currDir); String fileName = currDir + File.separator + f; File file = new File(fileName); if(file.exists()) { System.out.println("\n File '"+file.getName()+"' already existed"); } else { try { file.createNewFile(); System.out.println("\n File '"+file.getName()+ "' created successfully "); System.out.println("\n Path of '"+file.getName()+ "' file is : "+file.getAbsolutePath()); } catch(IOException ioe) { System.out.print(ioe); } } }// main() closed }// class closed
Output
When you will execute the above example you will get the output (white marked on console) as follows :