Remove hardcoded file path from java program

Tags: , , , ,



I have created a simple java program in which I create a text file and read the data written in it. The problem is that I don’t want to hardcode the path of the file because after developing the application I created a installer package for my program which allows users to install it on their systems. Now the problem is how the end users can install the file anywhere (i.e. in their C , D or E drive) and in those cases I get the FileNotFoundException exception.

My code – This is the code I use to create and write some text to the text file.

FileWriter file = new FileWriter("E:\TextFile.txt",true);
BufferedWriter writer = new BufferedWriter(file);
writer.write(input);
write.newLine();
write.close();

This is the code which I use to read text from the text file.

FileReader read = new FileReader("E:\TextFile.txt");
BufferedReader data = new BufferedReader(read);

I have another file for which I hardcoded the path of the file.

System.setProperty("webdriver.chrome.driver","D:\New Folder\chromedriver.exe");

As you can see in all my code I hardcoded the paths (“E:TextFile.txt”, “E:TextFile.txt” and “D:New Folderchromedriver.exe”). Is there any way in java to remove them? I went through the similar questions, but was not able to figure out how to detect the location of the file.

Answer

I made the changes as per the suggetions and it worked for me-

// This give me the path of the application where it is installed
String Path = new File("").getAbsolutePath();

Then i add the file name along with the path to get the file.

// Here i am adding the name of the file to the path to read it 
FileReader  read = new FileReader(Path+"\TextFile.txt"); 

// Here i am adding the name of the file to the path to write it 
FileWriter file = new FileWriter(Path+"\TextFile.txt",true);


Source: stackoverflow