Preferred method for saving/accessing text files
Hello, I have a question regarding the most correct way to access text files for editing/saving. My application currently just uses a local directory on my machine, but I need it to work on any machine once deployed. Is there a way to save a text file in my package and edit/save it later? I have looked at the getClass().getResource("fileName.ext") method, but this will not work with my static save method. If not, is there a preferred location to store files generated by the application? Thanks!
Re: Preferred method for saving/accessing text files
Quote:
is there a preferred location to store files generated by the application?
It's up to the application. Putting the file in the same folder as the jar file is simpler.
Quote:
save a text file in my package
What do you mean by "my package"? Is that a folder in your IDE?
Quote:
way to access text files for editing/saving
You can use the FileReader wrapped in a BufferedReader to read the file and use the corresponding set of classes named FileWriter and BufferedWriter to write them.
Re: Preferred method for saving/accessing text files
Norm,
Thanks for the response. I think my question wasn't clear enough. I am currently using BufferedReader and BufferedWriter to access and edit my file, but I am referencing locally. Example:
Code:
File file = new File("/my/local/directory/SQL.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
I need to change "/my/local/directory/SQL.txt" to something meaningful for app deployment. From my googling I have found the following:
Code:
InputStream is = DatabaseActions.class.getResourceAsStream("SQL.txt");
However I am not sure where my txt file needs to be in order for this to work. I have tried the application root and the folder that contains the .class files.
Re: Preferred method for saving/accessing text files
Re: Preferred method for saving/accessing text files
Quote:
I am not sure where my txt file needs to be in order for this to work
Use the getResource() method to return a URL and print it out to see the location.
For example This code:
System.out.println("loc=" + TestCode8.class.getResource("TestCode8.java"));
printed this:
loc=file:/D:/JavaDevelopment/Testing/ForumQuestions7/TestCode8.java
Make many copies of the SQL.txt file and put them in all the folders that are on the classpath when you execute the program. When the above code finds the file it will print out the URL showing the files location.
Re: Preferred method for saving/accessing text files
Quote:
Originally Posted by
Norm
System.out.println("loc=" + TestCode8.class.getResource("TestCode8.java"));
Worked..thanks!