0

I saved the runnable JAR file to another directory (not in the project folder). Now, I can read data from the runnable JAR file, but I can't write any data in file.

Code for reading data:

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader()
            .getResourceAsStream("TaskList.txt")));
    StringBuilder sb = new StringBuilder();
    String line = null;
    
    while((line = reader.readLine()) != null) {
        sb.append(line + "\n");
        textArea.setText(sb.toString());
    }
    reader.close();
}
catch(Exception ex) {
    JOptionPane.showMessageDialog(null, "File Not Found");
}

Code for writing data:

try{
    String content = textArea.getText();
    Writer writer = new OutputStreamWriter(new FileOutputStream("bin/TaskList.txt"));
    writer.write(content);
    writer.close();
}
catch(Exception ex) {
                
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
CSE
  • 73
  • 6

1 Answers1

2

Once you have compiled a JAR, the files within cannot be changed. A similar question to this has been asked and answered here.
An explanation for why you cannot do this is, a JAR is similar to a ZIP file. In order to change something inside it must be unzipped, edited, then rezipped. This is the same for archive files like rar or 7z. If you need to write to a file, the file must be local, and can't be within the archived JAR.

  • Would https://www.baeldung.com/java-compress-and-uncompress be also an option? – Reporter Jun 13 '22 at 11:04
  • @Reporter that could work, but I would have worries about unzipping a currently running JAR. Windows, and any other OS, will probably put file protections on it. Meaning you would have to copy the JAR, do the unzipping and editing, then on program close attempt to replace them. This is probably more complex then just having an external file. – Jackson Brienen Jun 13 '22 at 11:07
  • The questioner wrote that he was able to save the jar file into a different location. – Reporter Jun 13 '22 at 11:09
  • @Reporter Its possible I am misunderstanding the question. But from him getting "TaskList.txt" by `new InputStreamReader(getClass().getClassLoader() .getResourceAsStream("TaskList.txt"))` that infers that It is internally in the JAR. Which since its internally in the JAR, it is probably not worth the effort to change it. – Jackson Brienen Jun 13 '22 at 11:17