How to Construct a File Path in Java


In this example we will show how to construct a file path in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator2Example { 
	public static void main(String[] args )
    {	
    	try
    	{ 
    		String floderName = System.getProperty("user.dir");;
    		String fileName = "example.txt";
    		String filePath = floderName + File.separator + fileName;;
    		File file = new File(filePath); 
    		if (!file.exists())
		    { 
		    	file.createNewFile();
		    	System.out.println("The file is created.");
		    }
		    else
		    {
		    	System.out.println("The file already exists.");
		    }
    		System.out.println("filepath:"+filePath);
    	} 
    	catch (IOException e) 
    	{
    		e.printStackTrace();
    	}
    }
}

Output:

The file is created.
filepath:D:Workspacescasesexample.txt
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments