此代码在我的本地运行良好,但在我们使用 bamboo 构建时出现文件未找到异常。任何想法/解决方法?
final static String FILE_NAME ="/src/test/java/com/statement/SamplePDFStatementFile.txt";
file = new File(FILE_NAME);
FileInputStream fis = new FileInputStream(file);
我基本上想测试一个读取文件的类。这是完整的代码。
//Main Class
public class PdfRenderer {
public void render(PdfFile pdfFile) throws IOException {
FileInputStream fis = new FileInputStream(pdfFile.getFile());
final HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.setHeader("Content-Disposition", " attachment; filename=" + pdfFile.getAttachmentName());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
response.getOutputStream().write(buff, 0, bytesRead);
}
response.getOutputStream().flush();
}
}
//Test
public class PdfRendererTest{
PdfFile pdfFile;
File file;
@Test
public void test_DetailStatementsByAccountNumber() throws Exception {
new AbstractSeamTest.ComponentTest() {
PdfRenderer actionBean = new PdfRenderer();
URL url = this.getClass().getResource("/SamplePDFStatementFile.txt");
final String FILE_NAME = url.getFile();
protected void testComponents() throws Exception {
file = new File(FILE_NAME);
context.checking(new Expectations() {{
one(pdfFile).getFile();
will(returnValue(file));
one(pdfFile).getAttachmentName();
will(returnValue(file.getName()));
}});
actionBean.render(pdfFile);
}
}.run();
}
}
我想设置 pdfFile.getFile() 返回 SamplePDFStatementFile.txt 的预期。如果我使用 getResourceAsStream,我不确定如何将其转换为文件对象。
好的..所以现在我正在使用。看起来这就是答案:)
public void inputStreamToFile() throws Exception{
InputStream inputStream = this.getClass().getResourceAsStream("/SamplePDFStatementFile.txt");
file = File.createTempFile("abc","def");
OutputStream out = new FileOutputStream(file);
int length = 0;
byte[] bytes = new byte[1024];
while ((length = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, length);
}
inputStream.close();
out.flush();
out.close();
}
最佳答案
没有可靠的方法来引用相对于项目根文件夹的文件。
您需要将此文件作为资源引用。据我所知,您使用 Maven。如果是这样,您需要将此文件放入 /src/test/resources
而不是 /src/test/java
(也许您还可以配置 Maven 从 /src/test/java
,但这会违反 Maven 目录布局约定。
之后你可以将这个文件加载为
InputStream fis = getClass()
.getResourceAsStream("/com/statement/SamplePDFStatementFile.txt");
或者,如果当前类在com.statement
包中,如
InputStream fis = getClass().getResourceAsStream("SamplePDFStatementFile.txt");
关于java - 从当前包中获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7893274/