为什么无法打开这个文件?java.io.FileNotFoundException

image

package com.abbott.common.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class HtmlUtil {
    public static void exportHtml() {
        //用于存储html字符串
 StringBuilder stringHtml = new StringBuilder();
 try {
            //打开文件
 PrintStream printStream = new PrintStream(new FileOutputStream("./Data/test.html"));
 //输入HTML文件内容
 stringHtml.append("<html><head>");
 stringHtml.append("<meta http-equiv="Content-Type" content="text/html; charset=GBK">");
 stringHtml.append("<title>测试报告文档</title>");
 stringHtml.append("</head>");
 stringHtml.append("<body>");
 stringHtml.append("<div>hello</div>");
 stringHtml.append("</body></html>");
 try{
                //将HTML文件内容写入文件中
 printStream.println(stringHtml.toString());
 }catch (Exception e) {
                e.printStackTrace();
 }
        } catch(FileNotFoundException e){
            e.printStackTrace();
 }
    }
    public static void main(String[] args) {
        HtmlUtil.exportHtml();
 }
}
阅读 3k
4 个回答

文件路径不正确,不是无法打开文件,而是程序找不到这个文件...
如果要生成这个文件需要new File(“xxx”)

ps:字符串里面要转译啊

新手上路,请多包涵

系统找不到指定的路径image

如下,这样就可以了。
文件的路径输入的有问题。
image

新手上路,请多包涵
PrintStream printStream = new PrintStream(new FileOutputStream("./Data/test.html"));

这行改成下面这样试试,下面这样文件会被创建到当前目录的 test.html:

PrintStream printStream = new PrintStream(new FileOutputStream("./test.html"));

十有八九你是没在当前目录创建 Data 这个文件夹,如果你前面的代码要能正确执行,你先把 Data 文件夹创建好了也行。

新手上路,请多包涵

你尝试从 classpath 下读取文件。

如不是特殊需求,你应该将 test.html 放到 resource 目录下。

classpath 下读取文件参考下面链接中的教程。

https://blog.csdn.net/jiaobuc...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题