0

I'm simply trying to add a new line of text to my *.txt file, but nothing happens at all. The file is packed with a .war, so I use a ClassLoader to access the file. Also, both my eclipse IDE, and the contents of the file, use UTF-8 encoding.

I've used these for inspiration:

How to add a new line of text to an existing file in Java?

Java BufferedWriter object with utf-8

Now my code is mainly based on the last post, and looks like this:

public class test {


    public static void main(String[] args){

        URL url = Thread.currentThread().getContextClassLoader().getResource("MilestoneExport.txt");

        File file = new File(url.getFile());

        System.out.println(file.canRead()); //true
        System.out.println(file.canWrite()); //true


        try {
            BufferedWriter out = new BufferedWriter
                (new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
            out.append("new line");
            out.append("new line 2");
            out.append("new line 3");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }
}

I've confirmed that the file is in fact found, and it reads fine. I've been able to output the entire content of it to the console through the use of a BufferedReader. The path of the file is also correct, but absolutely no text is added to the file. I've made sure that I have refreshed and updated every time I've run the program.

Also, I've tried to create a simple empty file called foo.txt, which is located in the same directory as test.java. I added the following code to the main method, as provided by the BufferedWriter API, at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html

PrintWriter out2 = new PrintWriter(
    new BufferedWriter(new FileWriter("foo.txt")));
out2.println("new Line");
out2.close();

What am i missing here? Why are there no error messages, and no responses or feedbacks whatsoever?

EVERYTHING BELOW IS ONLY ADDITIONAL INFO ABOUT WHAT I'VE TRIED. NO FEEDBACK IN ANY CASES:

Also, this code, from this answer, does nothing as well...

try {
        BufferedWriter output = new BufferedWriter(new FileWriter(new File("house.txt")));

        output.write("text");
        output.close();
    } 
    catch (IOException e) {
        e.printStackTrace();
    } 

last but not least, I suspected that it might have something to do with the packaging of my Web-App, and differences between the source and target-folders. So I copied the code to a brand new clean project, but it still does nothing at all...

EDIT:

this code:

System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getName());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.setLastModified(new   GregorianCalendar().getTimeInMillis()));

gives these outputs:

  • true
  • D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
  • D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
  • MilestoneExport.txt
  • false
  • true
  • true

Am I completely misunderstanding the use of java's File-objects, and it's uses with FileWriters? The file is clearly 100% confirmed the correct file.

Community
  • 1
  • 1
jumps4fun
  • 3,994
  • 10
  • 50
  • 96

4 Answers4

1

You should use the other constructor of FileOutputStream in order to open the file in append mode :

FileOutputStream(File file, boolean append)

I.e,

new FileOutputStream(file, true)

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Sorry that I've forgot to mention that, but I've tried that one as well. First actually. Still no response or output of any kind. As long as absolutely none of these work, the issue is probably something completely different. I've tried too many different things to think it is a syntax issue. Writing sinmply does not work in any form, and I have no idea of what the problem might be? – jumps4fun Jul 15 '14 at 13:17
0

Since I can't comment, you might not be saving the file back into the archive it came from (I'm not sure if java supports writing to the internal structures of archives by editing the files that are included, however you might want to try to store the file externally to the archive to see if that is the place the issue comes from).

The cause of what you posted in the comments is that your IDE won't extract the resource file from a compiled program, if you want to sync the internal data you might be able to setup a client-server connection using sockets and creating a program that writes the data to the local file from data packets send to your web-app, otherwise retrieving the edited file from where you are hosting might be less complicated (or if you are deploying from the same PC you might be able to get away with a symbolic or hard link)

Dark Eye
  • 67
  • 2
  • I think you are on to something here. The file is definitely found, but it is not changed, or maybe it is saved back to another location? I think I need to do a computer search. – jumps4fun Jul 15 '14 at 13:25
  • This is actually the best answer here. Welcome to Stack Overflow by the way. It would be nice if you would expand this answer, so that it contains a little more detail, and I'll provide you with it. My file is loaded from the source folder of my web application, and when the web-app is packaged, it is packaged into the target folder. here it is retrieved when the web-app starts. As long as The web-app is never restarted, the file can be written to, and read from. But this will not reflect in my IDE's source folder. if I continue to develop, and deploy new versions, the new data will be lost. – jumps4fun Jul 15 '14 at 14:14
0

I've tried this code that is very similar to yours and it's working nicely, so i think the problem is the way you are picking the path of the file.

public static void main(String[] args){

    File file = new File("./localtest.txt");

    System.out.println(file.canRead()); //true
    System.out.println(file.canWrite()); //true


    try {
        BufferedWriter out = new BufferedWriter
            (new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
        out.append("new line");
        out.append("new line 2");
        out.append("new line 3");
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
}
Rafael
  • 2,521
  • 2
  • 33
  • 59
  • Thanks. Confirmation that some of the code is working other places is very valuable to me. – jumps4fun Jul 15 '14 at 13:22
  • I have been able to confirm the path of my file though, so retrieving the file works perfectly. Shouldn't I be able to write back to the same file and path I found earlier? – jumps4fun Jul 15 '14 at 13:24
  • May I ask if your file was already existing, or if it was created by your code? Where in your directory structure did it end up? I've tried the exact same code, but it is not working here, as far as I can tell. – jumps4fun Jul 15 '14 at 13:36
  • The file did not exist in my example was created new. If it helps i tend to use the newest Java 7 classes Files.newBufferedWriter(Paths.get("URL"), StandardCharsets.UTF_8 , StandardOpenOption.APPEND). Note that StandardCharsets and StandardOpenOption are enum classes so you can check possible values. Also it is a common practice to use Apache IO libraries to make these operations easier since it hides some of the complexities of the file IO operations. Finally please do not forget to flush and close files. Hope some of this suggestions may help you. – Rafael Jul 16 '14 at 12:56
0

this works

 PrintWriter pw= new PrintWriter(
    new BufferedWriter(new FileWriter("C:\\foo.txt")));
    pw.println("line 1");
    pw.close();
AeOn
  • 37
  • 1
  • 7
  • It does. One thing all of the answers here seem to have in common, is that the target location of the file I'm writing to needs adjustment. – jumps4fun Jul 15 '14 at 13:27