0

Currently I'm developing a java application to carry out a survey. I want to read/write to a .txt file, creating a .csv to store inputted data. Below is code I have used so far to write data - Of course this makes the JAR file not portable as it has an absolute path.

File file = new File("C:/Files/JavaApp/src/text.text/");
FileWriter fw = null;
BufferedWriter bw = null;
try {
    fw = new FileWriter(file, true);
} catch (IOException e) {
    System.out.println(e.getMessage());
}
bw = new BufferedWriter(fw);
try {
    bw.write("blah" + ",");
} catch (IOException e) {
    System.out.println(e.getMessage());
}
try {
    bw.newLine();
} catch (IOException e) {
    System.out.println(e.getMessage());
}
try {
    bw.close();
} catch (IOException e) {
    System.out.println(e.getMessage());
}

I have tried several methods such as ClassName.class.getResource("Text.text"); but it will always return a Reflection or a NullPointer error.

I know that writing to a file within the JAR does pose some problems, meaning I would have to point to a file outside to read/write. However I don't know how to preform this in code. I need the JAR file to be completely portable. Even if that means it must be kept within a directory, so the JAR can search for the .txt file within that directory. Or, is there another way?

If anyone can help me out, I would be very grateful.

Rhys
  • 3
  • 1
  • 4
  • don't know if you can use it for that, but try the package java.util.jar (http://docs.oracle.com/javase/7/docs/api/java/util/jar/package-summary.html) – herrlock Dec 05 '14 at 23:33
  • 2
    and also read this answer http://stackoverflow.com/a/5052359/3680684 – herrlock Dec 05 '14 at 23:35
  • It's not clear what is being asked. The only question in this post is "Or, there is another way?". What do you want to accomplish? – VGR Dec 05 '14 at 23:42
  • possible duplicate of [How can an app use files inside the JAR for read and write?](http://stackoverflow.com/questions/5052311/how-can-an-app-use-files-inside-the-jar-for-read-and-write) – A4L Dec 05 '14 at 23:51
  • 1
    Thank you for your replies. Some good links, I hadn't seen before. – Rhys Dec 06 '14 at 18:44

1 Answers1

1

To read from the Jar file: How to read a file from jar in Java?

The file is an archive file. It is a zip file with a .jar extension. You shouldn't be writing to it. If the jar file has been signed (security projected) you cannot write to it. Changing a single bit in the file will invalidate it.

What you should do is store a default file in Jar and load that to the "user.home" folder if it is not already there.

Community
  • 1
  • 1
Timothy Wright
  • 351
  • 2
  • 11