代码之家  ›  专栏  ›  技术社区  ›  Vicky

如何在JUnit中的临时目录中添加文件

  •  0
  • Vicky  · 技术社区  · 6 年前

    我发现了两种在JUnit中创建临时目录的方法。

    方式1:

    @Rule
    public TemporaryFolder tempDirectory = new TemporaryFolder();
    
    @Test
    public void testTempDirectory() throws Exception {
        tempDirectory.newFile("test.txt");
        tempDirectory.newFolder("myDirectory");
        // how do I add files to myDirectory?
    }
    

    方式2:

    @Test
    public void testTempDirectory() throws Exception {
        File myFile = File.createTempFile("abc", "txt");
        File myDirectory = Files.createTempDir();
        // how do I add files to myDirectory?
    }
    

    正如上面的评论所提到的,我需要在这些临时目录中添加一些临时文件。对这个结构运行我的测试,最后在退出时删除所有内容。

    我该怎么做?

    2 回复  |  直到 6 年前
        1
  •  7
  •   Sasha Shpota A-Bag    6 年前

    您可以像处理真实文件夹一样执行此操作。

    @Rule
    public TemporaryFolder rootFolder = new TemporaryFolder();
    
    @Test
    public void shouldCreateChildFile() throws Exception {
        File myFolder = rootFolder.newFolder("my-folder");
    
        File myFile = new File(myFolder, "my-file.txt");
    }
    
        2
  •  1
  •   tklaus    4 年前

    使用新文件(临时文件夹的子文件夹“fileName”)对我不起作用。调用子文件夹.list()返回一个空数组。我就是这样做的:

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();
    
    @Test
    public void createFileInSubFolderOfTemporaryFolder() throws IOException {
        String subFolderName = "subFolder";
        File subFolder = temporaryFolder.newFolder(subFolderName);
        temporaryFolder.newFile(subFolderName + File.separator + "fileName1");
    
        String[] actual = subFolder.list();
    
        assertFalse(actual.length == 0);
    }
    
        3
  •  -3
  •   TongChen    6 年前

    有两种方法可以删除临时目录或临时文件。首先,使用file.delete()方法手动删除目录或文件,其次,当程序退出用户文件时删除临时目录或文件。deleteOnExist()。

    File myDirectory = Files.createTempDir();
    File tmpFile = new File(myDirectory.getAbsolutePath() + File.separator + "test.txt");
    FileUtils.writeStringToFile(tmpFile, "HelloWorld", "UTF-8");
    System.out.println(myDirectory.getAbsolutePath());
    // clean
    tmpFile.delete();
    myDirectory.deleteOnExit();