写入文件,输出文件在哪里? [英] Writing to a file, where is the output file?

查看:198
本文介绍了写入文件,输出文件在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  FileWriter outFile = null; 
try {
outFile = new FileWriter(member.txt);
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
out.println(test);

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

解决方案

Java IO中的相对路径与当前工作目录相关。在Eclipse中,通常是项目根。您还写入 out 而不是 outFile 。这是一个小的重写:

 文件文件=新文件(member.txt); 
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write(test);
} catch(IOException e){
e.printStackTrace(); //我宁愿使用throws IOException声明方法,并省略此catch。
} finally {
if(writer!= null)try {writer.close(); } catch(IOException ignore){}
}
System.out.printf(文件位于%s%n,file.getAbsolutePath());

关闭是强制性的,因为它将写入的数据刷新到文件中并释放文件锁定。 >

不用说,在Java IO中使用相对路径是一个糟糕的做法。如果可以,使用类路径。 ClassLoader#getResource() getResourceAsStream()等等。


        FileWriter outFile = null;
        try {
            outFile = new FileWriter("member.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
out.println("test");

Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.

解决方案

Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:

    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());

Closing is mandatory since it flushes the written data into the file and releases the file lock.

Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.

这篇关于写入文件,输出文件在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆