I am so sorry if this has been posted before.
What I am trying to do is write and read a simple string to a file located in one of the packages in my project. Inside Source Packages I have a package called "resources". Here i want to read a file called myfile.txt
, do some stuff with it and save it again as newmyfile.txt
. Just simple reading and storing of CSV data.
I have created a reader, which looks like this:
public BufferedReader getFileReader(String fileNameWithExtension, String sourcePackage) {
try {
String file = "/" + sourcePackage + "/" + fileNameWithExtension;
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
return br;
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return null;
}
}
This works fine on my Mac. Reading up on this i find out that i have to use File.separator in order to get it to work on all operating systems. So i change this, and still it don´t work. Somewhere it is said that a relative path always starts with /
regardless of operating system when using relative paths, and other places ../
. As a complete newbie on file storage on Java, I am confused.
There is also a lot of ways to read and write files, and I don´t know what method to choose, and why.
What is the best way for me to read and create files where all I want to do is save one long string, or an array of strings?