【发布时间】:2011-10-25 17:25:56
【问题描述】:
此代码在我的本地运行良好,但在我们使用竹子构建时出现文件未找到异常。有什么想法/解决方法吗?
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();
}
【问题讨论】:
-
当你 build 或 run 它时它会给出异常?
-
了解如何使用类加载器(上下文类加载器,或加载当前类的类)中的
getResource方法,使用从根包 (com) 开始的路径。您似乎使用的是绝对路径。 -
看起来文件在 SRC 文件夹下,通常构建排除 SRC 文件夹,你能检查一下吗?