Ok, I have a .txt file stored inside a folder “res” inside my JAR-file. I can read from that file with the following method.
public String[] loadText(String path){
InputStream mySettingsStream = FileLoader.class.getResourceAsStream("/res/"+path);
String mySettingsString = "null";
StringBuilder build = new StringBuilder();
int i = 0;
try {
while((i = mySettingsStream.read()) != -1) {
build.append((char)i);
}
mySettingsString = build.toString();
return mySettingsString.split("\r\n");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
However, I want to be able to store changes I’ve made to the data in that file and I can’t figure out how to do that. I tried using an OutputStreamWriter with a URL (as you can see below) but it caused a “java.net.UnknownServiceException: protocol doesn’t support output” so I clearly need something else.
If possible I want to even be able to create a new .txt file at the location in case one with the name from path doesn’t exist.
public void write(String path, String[] lines){
if(path==null || lines==null){return;}
URL url = FileLoader.class.getResource("/res/" + path);
try {
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
for(int i = 0; i < lines.length; i++){
out.write(lines[i]);
}
out.close();
} catch (IOException e) {
System.err.println("Failed to write to file");
e.printStackTrace();
}
}
Anyone have any ideas?
I know that it might not be the best idea to mess around with changing and creating files inside a JAR file but it’d be great if I could do it safely. At the very least I’d like to have the ability to edit text files in there.