我正在尝试在Web应用程序目录中创建一个文件 TestFile.db 。但到目前为止我一直没有成功。我不明白原因。
尝试创建文件的JSP代码段:
<% if(new FileMaker().makeFile()) {%>
<h2>File Creation successful !</h2>
<%} else {%>
<h2>Unable to create a file !</h2>
<%}%>
尝试制作文件的类:
public class FileMaker {
private boolean success = false;
public boolean makeFile() {
try {
File f = new File("TestFile.db"); // CREATE A FILE
PrintWriter writer = new PrintWriter(f);
writer.println("This is a test statement on a test file");
writer.close();
success = true;
}catch(Exception exc) {
exc.printStackTrace();
return success;
}
return success;
}
}
名为App-1
结构的网络应用程序如下:
上面的代码不会创建任何异常并返回true
但我没有看到任何文件被创建。这是为什么 ?但如果我改变声明如下:
File f = new File("/App-1/TestFile.db");
我收到一个未找到文件的异常。我不明白这个的原因。请解释这两个案例。 如何在目录App-1
中创建文件?
答案 0 :(得分:2)
您需要提供filemaker的正确路径。您可以通过从servlet上下文获取正确的路径来完成此操作。
<%@page import="com.adtest.util.FileMaker"%>
<% if(new FileMaker().makeFile(this.getServletContext().getRealPath("/"))) {%>
<h2>File Creation successful !</h2>
<%} else {%>
<h2>Unable to create a file !</h2>
<%}%>
接下来在你的filemaker类中添加路径,只有在它没有延伸时才创建。
public boolean makeFile(String path) {
try {
File f = new File(path+"\\TestFile.db"); // CREATE A FILE
if(!f.exists())
f.createNewFile();
PrintWriter writer = new PrintWriter(f);
writer.println("This is a test statement on a test file");
writer.close();
success = true;
}catch(Exception exc) {
exc.printStackTrace();
return success;
}
return success;
}
答案 1 :(得分:0)
尝试调试并使用f.getAbsolutePath()来获取创建文件的路径。因此,当您收到路径时,您可以修改它。随着更多信息的到来,请更新问题。 您收到的文件未找到,因为它似乎没有实际创建。你真的调用mkFile()命令吗? :)
如果exists()返回false,请执行以下操作:
file.createNewFile("fileName");
//write some data to file.
createFileName()创建绝对空白的新文件。