我有一个单元测试,需要使用位于src/test/resources/abc.xml中的XML文件。将文件内容放入字符串的最简单方法是什么?


当前回答

你可以使用Junit Rule为你的测试创建一个临时文件夹:

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
File file = temporaryFolder.newFile(".src/test/resources/abc.xml");

其他回答

好的,对于JAVA 8,经过大量的调试 我发现两者之间是有区别的

URL tenantPathURI = getClass().getResource("/test_directory/test_file.zip");

and

URL tenantPathURI = getClass().getResource("test_directory/test_file.zip");

是的,在路径开始的/没有它,我得到null!

test_directory在test目录下。

你可以使用Junit Rule为你的测试创建一个临时文件夹:

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
File file = temporaryFolder.newFile(".src/test/resources/abc.xml");

多亏了Apache Commons,我终于找到了一个简单的解决方案:

package com.example;
import org.apache.commons.io.IOUtils;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = IOUtils.toString(
      this.getClass().getResourceAsStream("abc.xml"),
      "UTF-8"
    );
  }
}

完美的工作。文件src/test/resources/com/example/abc.xml被加载(我使用Maven)。

如果你将“abc.xml”替换为“/foo/test.xml”,这个资源将被加载:src/test/resources/foo/test.xml

你也可以使用仙人掌:

package com.example;
import org.cactoos.io.ResourceOf;
import org.cactoos.io.TextOf;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = new TextOf(
      new ResourceOf("/com/example/abc.xml") // absolute path always!
    ).asString();
  }
}

你可以试试:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

这是我用来获得文本文件与文本。我使用了commons的IOUtils和guava的Resources。

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}