简体   繁体   English

为什么我不能在 A junit 测试中写入文件?

[英]Why cant i write to a file in A junit test?

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我有一个 junit 测试套件,用于测试写入、编辑和删除这些文件的一些操作

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:所以我在 @beforeClass 测试方法中有以下代码:

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.如果文件不存在,.write() 应该创建一个新文件。

using File.canwrite() confirms this by returning false.使用 File.canwrite() 通过返回 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?所以我的问题是,当它在主代码中运行良好时,为什么我不能在测试中写入文件?

It appears I just needed to create the new directories before I tried to write files in them.看起来我只需要在我尝试在其中写入文件之前创建新目录。 Silly mistake.愚蠢的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM