-2

我有一个在 tomcat 上运行的 web 服务,并且想要执行一些 fileIO。

File f = new File(test.txt);
new BufferedReader(new FileReader(test.txt));

结果:

java.io.FileNotFoundException: test.txt
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:97)
    at java.io.FileReader.<init>(FileReader.java:58)

我错过了什么吗?将我的代码作为本地独立应用程序运行可以按预期工作。但是在tomcat上会导致异常。

4

3 回答 3

4

您需要先创建文件。File 对象实际上只是文件路径的表示,而不是文件本身。

f.createNewFile()
于 2012-08-08T17:20:58.327 回答
2
if (!f.exists())  
{  
   f.createNewFile();   
}
于 2012-08-08T17:24:06.483 回答
0

Running my code as a local standalone app works as expected. But on tomcat results in exception.

You are using a path relative to the working directory. When you run it as a stand alone app, I assume you have the file in the directory you run the app from. The working directory for a web server is often the bin of the server so you are saying you expect the file to be there.

Using a full path, or using a resource of your application with getResourceAsInputStream() is a better idea.

于 2012-08-08T18:13:22.640 回答