Home > Net >  Why cant i write to a file in A junit test?
Why cant i write to a file in A junit test?

Time:10-08

I have a directory with some files in it.

I have a junit test suite that tests some operations that write, edit and delete these files

I want to save the contents of the files before I run the tests and restore them after.

I am trying to do this by copying the files to another directory before the tests run and copying them back after.

so I have the following code in an @beforeClass test method:

File repDir = new File("/home/hamster339/Documents/Projects/Piping_Tune_List/Repertoire");
    if (repDir.exists()){
        for (File f: Objects.requireNonNull(repDir.listFiles())) {
            Scanner r = new Scanner(f);
            FileWriter w = new FileWriter(String.format("/home/hamster339/Documents/Projects/Piping_Tune_List/temp/%s",f.getName()));
            while (r.hasNextLine()){
                w.write(r.nextLine());
            }
            w.close();
            r.close();
        }
    }

However, this gives me the following error:

java.io.FileNotFoundException: /home/hamster339/Documents/Projects/Piping_Tune_List/temp/Learnt.prl (No such file or directory)

This error indicated, from my understanding, that I do not have write permission. .write() should create a new file if one does not exist already.

using File.canwrite() confirms this by returning false.

Writing works perfectly fine in the main program, and I also am able to make new directories, just not write to or create files.

so my question is, why can't I write to files in the tests, when it works fine in the main code?

CodePudding user response:

It appears I just needed to create the new directories before I tried to write files in them. Silly mistake.

  • Related