加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 写入文件,输出文件在哪里?

发布时间:2020-12-15 04:52:57 所属栏目:Java 来源:网络整理
导读:FileWriter outFile = null; try { outFile = new FileWriter("member.txt"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }out.println("test"); 运行该命令,member.txt在哪里?我正在使用Windows vista. UAC启用
FileWriter outFile = null;
        try {
            outFile = new FileWriter("member.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
out.println("test");

运行该命令,member.txt在哪里?我正在使用Windows vista. UAC启用所以当我运行它时,我不认为它正在写入txt文件.但是创建了txt文件,但它是空的.

解决方法

Java IO中的相对路径与当前工作目录相关.在Eclipse中,通常是项目根目录.你也写出来而不是outFile.这是一个小改写:

File file = new File("member.txt");
    FileWriter writer = null;
    try {
        writer = new FileWriter(file);
        writer.write("test");
    } catch (IOException e) {
        e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
    } finally {
        if (writer != null) try { writer.close(); } catch (IOException ignore) {}
    }
    System.out.printf("File is located at %s%n",file.getAbsolutePath());

关闭是必需的,因为它将写入的数据刷新到文件中并释放文件锁.

不用说,在Java IO中使用相对路径是一种不好的做法.如果可以,而是使用类路径. ClassLoader#getResource(),getResourceAsStream()等等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读