1

在Java中,我们可以通过...创建对文件的引用...

File counterFile = new File("countervalue.txt");

但是如果文件不存在,我们如何创建它呢?

4

2 回答 2

2

创建文件的基本方法是调用File#createNewFile方法:

File counterFile = new File("countervalue.txt");
try {
    counterFile.createNewFile();
} catch (Exception e) {
    System.out.println("File couldn't been created.");
}

现在,如果您想创建一个新文件并用数据填充它,您可以将 aFileWriter和 aPrintWriter用于文本文件(假设这是txt示例中的扩展名):

File counterFile = new File("countervalue.txt");
PrintWriter pw = null;
try {
    //it will automatically create the file
    pw = new PrintWriter(new FileWriter(counterFile));
    pw.println("Hello world!");
} catch (Exception e) {
    System.out.println("File couldn't been created.");
} finally {
    if (pw != null) {
        pw.flush();
        pw.close();
    }
}

如果您只想将数据附加到文件中,请使用作为第二个参数FileWriter(File, boolean)传递的构造函数:true

pw = new PrintWriter(new FileWriter(counterFile, true));
于 2012-10-27T16:35:48.650 回答
1

用java轻松完成

File counterFile = new File("countervalue.txt");
counterFile.createNewFile();
于 2012-10-27T16:35:40.757 回答