我正在尝试在 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
中创建文件?
最佳答案
您需要提供 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;
}
关于java - 无法在 Web 应用程序目录中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14361923/