Reputation: 1462
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 Folder\chromedriver.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.
Upvotes: 4
Views: 11601
Reputation: 1462
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);
Upvotes: 3
Reputation: 897
I don't think this the answer to what you are asking, but It's a solution to your problem. What you are using there is an absolute path, meaning you specify the whole URL of the file, you can instead use relative paths, which are relative to the location of your application, just like you have .class files in your JAR, you can have a folder for your files and it will be always at the same location relative to the program location.
So instead of this:
FileReader read = new FileReader("E:\\TextFile.txt");
You can have this:
FileReader read = new FileReader("..\MyFiles\TextFile.txt");
Or something like this.
Upvotes: 0
Reputation: 1375
You can store the file location in a properties file and then read the file location from that into a variable at runtime. Your installer would have to store the file location in the properties file as part of its installation process.
You could also have the file stored in the applications classpath and use relative pathnames to get to it.
Upvotes: 0