Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果文件尚未存在,请创建该文件_Java_File_Io - Fatal编程技术网

Java 如果文件尚未存在,请创建该文件

Java 如果文件尚未存在,请创建该文件,java,file,io,Java,File,Io,在Java中,我们可以通过以下方式创建对文件的引用 File counterFile = new File("countervalue.txt"); 但是,如果文件不存在,我们如何创建它呢?用java轻松完成 File counterFile = new File("countervalue.txt"); counterFile.createNewFile(); 创建文件的基本方法是调用以下方法: 现在,如果您想创建一个新文件并用数据填充它,可以对文本文件使用FileWriter和Print

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

File counterFile = new File("countervalue.txt");
但是,如果文件不存在,我们如何创建它呢?

用java轻松完成

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

创建文件的基本方法是调用以下方法:

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

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

pw = new PrintWriter(new FileWriter(counterFile, true));
如果(!f.exists())f.createNewFile()
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();
    }
}
pw = new PrintWriter(new FileWriter(counterFile, true));