Skip to content
Advertisement

Remove hardcoded file path from java program

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.

JavaScript

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

JavaScript

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

JavaScript

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.

Advertisement

Answer

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement