File Path – Constructing file path in Java

Often we read /write files from particular directory. We need to construct a file path, where we want to create a file or read files from that directory. Directory file path will be separated with back slash (\) or forward slash (/), these will be specific to operating system (windows, Linux / Unix based). For writing common logic, we use File.separator to get the forward slash (/) or back slash based on the operating system where we are running program.

File Path

package com.jminded.java.io;

import java.io.File;
import java.io.IOException;

/**
 * https://jminded.com
 * @author Umashankar
 *
 */
public class FilePath {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		// this is probably the dynamic file name
		String fileName = "myFile.txt";
		// working directory, get it from System properties
		String workingDirectory = System.getProperty("user.dir");

		// build absolute path
		String absolutePath = workingDirectory + File.separator + fileName;
		System.out.println(absolutePath);

		// get the file handle for the absolute path
		File file = new File(absolutePath);

		try {
			// call createNewFile() on the file handle, which actually creates file
			if (file.createNewFile()) {
				System.out.println("File is created!");
			} else {
				System.out.println("File already exists!");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("error creating file");
		}
	}

}

References

https://docs.oracle.com/javase/8/docs/api/java/io/File.html

Leave a Comment