在Java中,我们可以通过...创建对文件的引用...
File counterFile = new File("countervalue.txt");
但是如果文件不存在,我们如何创建它呢?
创建文件的基本方法是调用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));
用java轻松完成
File counterFile = new File("countervalue.txt");
counterFile.createNewFile();