Create File Path Java

Create File Path Java

Create file path is very important whenever you want to make it compatible and work on different operating systems. For example if you have written a batch job which creates file on network on different machine and those are Unix box and your development environment is window. If you use file separator like (“\”) to create file path which will work on window perfectly but won’t work on Unix environment because they use different file separator to separate the path as below:

Window: “\”
Unix: “/”

To make your file path compatible with different environment you could use below example to create file path:

Sample java class:

package com.javahonk;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFilePath {

	public static void main(String[] args) {
		
		String fileNameToCreate = "Test.txt";
		String userDirectory = System.getProperty("user.dir");
		
		//Example 1:
		File file = new File(userDirectory, fileNameToCreate);
		
		if (!file.exists()) {
			boolean fileCreated;
			try {
				fileCreated = file.createNewFile();
				if (fileCreated) {
					System.out.println("New file created:"+file.getName());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} else {
			System.out.println("File already exists");
		}
		
		
		//Example 2
		Path path = Paths.get(System.getProperty("user.dir"),"FilePathTest", "Test.log");
		
		file = new File(path.toString());
		
		if (!file.exists()) {
			boolean fileCreated;
			try {
				fileCreated = file.createNewFile();
				if (fileCreated) {
					System.out.println("New file created:"+file.getName());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} else {
			System.out.println("File already exists");
		}
		
		//Example 3
		fileNameToCreate = "Test3.txt";
		String createAbsoluteFilePath = userDirectory+File.separator+fileNameToCreate;
		file = new File(createAbsoluteFilePath);
		
		if (!file.exists()) {
			boolean fileCreated;
			try {
				fileCreated = file.createNewFile();
				if (fileCreated) {
					System.out.println("New file created:"+file.getName());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} else {
			System.out.println("File already exists");
		}
		

	}

}

Output:

Create File Path Java

For more information about path please visit oracle site here 

Leave a Reply

Your email address will not be published. Required fields are marked *