0

I wrote a java application which reads a file (files/olten) and displays the information in this file. (in a JTable). I now have problems with updating the information in the file so that the manipulations are not lost and on next opening of the program are still there.

I've tried many things to specify the path to the file but nothing worked. Here are some samples of what I tried:

out = new PrintWriter(new File("").getAbsolutePath() + "/files/olten");
out = new PrintWriter(this.getClass().getClassLoader().getResource("files/olten").toString());
out = new PrintWriter("olten");

the correct path (seen from the .java file's path) is "files/olten". How can I achieve to modify this file?

Thanks in advance!

Christian
  • 609
  • 8
  • 22
  • 1
    Similar to [this](http://stackoverflow.com/questions/5052311/how-can-a-java-program-use-files-inside-the-jar-for-read-and-write) and [this](http://stackoverflow.com/questions/1224817/modifying-a-file-inside-a-jar). – Zong May 25 '13 at 21:17

2 Answers2

1

Writing to a resource file that a part of your distributable jar is probably not the right thing to do. You may want to try something like this but the results might be different depending on how you might want to use you jar.

URL url = getClass().getResource(relative_path);
File file = new File(url.toURI());
OutputStream output = new FileOutputStream(file);

Still not recommended!!

Dhrubajyoti Gogoi
  • 1,265
  • 10
  • 18
0

You probably want to use FileWriter see this example :

try {
     PrintWriter writer = new PrintWriter(new FileWriter("files/olten/TextFile.txt",true));
     writer.println("Some text");
     writer.flush();
     writer.close();
     System.out.println("Writed");
   } catch (IOException ex) {
      //write your own message
   }

NOTE:
The parameter true indicates that the data will be written to the end of the file rather than the beginning.

Azad
  • 5,047
  • 20
  • 38
  • Unless `FileWriter` does so, this doesn't address his main issue, that is, to modify files inside a jar. – Zong May 26 '13 at 05:22
  • @ZongLi: but did I said that it he won't use *FileWriter* his problem won't solve? No, in fact there is 7 other constructor in *PrintWriter* with different parameter that he can use. – Azad May 26 '13 at 06:11
  • Your wording is a bit confusing, but it's logically equivalent to "I didn't say his problem will be solved if he used `FileWriter`". Well, making a tangential suggestion doesn't really suffice as an answer; it doesn't address his real problem. – Zong May 26 '13 at 07:50