【问题标题】:Application write in file from webapp tomcat7应用程序从 webapp tomcat7 写入文件
【发布时间】:2016-01-07 11:25:13
【问题描述】:

请,当我在 tomcat7/webapp/myapp.war 中部署应用程序并通过 Web 浏览器运行此应用程序时,我找不到输出文件。

我的应用程序存储一些结果文件如下:

try {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/home/user/Desktop/myfile.txt", true)));
            out.println("some text");
            out.close();
        } catch (IOException e) {
            //exception handling left as an exercise for the reader
        }

输出文件在哪里?

【问题讨论】:

  • 至少在上面的代码中,我看到您正在捕获 IOException 并默默地忽略它。如果在打开或写入文件时出现任何异常(权限、不存在等),您将不会了解它。您能否在 catch 块中添加 e.printStackTrace() 并检查 tomcat 日志以查看它是否抛出任何与文件相关的异常。

标签: java file tomcat7 printwriter


【解决方案1】:

它将在 webapps 目录下创建,即 myapp/home/user/Desktop/myfile.txt

【讨论】:

  • 呃,我没找到。我怎样才能在我的本地桌面上写它!?
  • 试试这段代码 PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("file:/home/user/Desktop/myfile.txt", true)));
【解决方案2】:

如果你想把它放在你的桌面上,你需要像这样在 home 前面放一个正斜杠 (/)

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/home/user/Desktop/myfile.txt", true)));

更新 - 尝试

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));

然后检查.../tomcat/bin/目录看看?

更新

好的 试试这个并检查您的桌面。我自己试过了,对我有用。

try {
        File file = new File("/home/user/Desktop/myfile.txt");
      // creates the file
      file.createNewFile();
      // creates a FileWriter Object
      FileWriter writer = new FileWriter(file); 
      // Writes the content to the file
      writer.write("This\n is\n an\n example\n"); 
      writer.flush();
      writer.close();    
        } catch (IOException e) {
            //exception handling left as an exercise for the reader
        }

【讨论】:

  • 对不起,我更新了我的问题。我用斜杠 (/) 做的,但我没有找到它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 2012-05-31
  • 2015-01-09
  • 2011-06-11
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多