Java教程

Java 程序创建文件并写入文件

Java 程序创建文件并写入文件

在这个例子中,我们将学习用 Java 创建文件并将一些信息写入文件。
要理解此示例,您应该了解以下Java 编程主题:
Java 文件类 Java FileWriter 类

示例 1: 创建文件的 Java 程序

// importing the File class
import java.io.File;
class Main {
  public static void main(String[] args) {
    // create a file object for the current location
    File file = new File("JavaFile.java");
    try {
      // create a new file with name specified
      // by the file object
      boolean value = file.createNewFile();
      if (value) {
        System.out.println("New Java File is created.");
      }
      else {
        System.out.println("The file already exists.");
      }
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}
在上面的例子中,我们创建了一个名为 file 的文件对象。文件对象与指定路径链接。
// javaFile.java is equivalent to
// currentdirectory/JavaFile.java
File file = new File("JavaFile.java");
然后我们使用 File 类的 createNewFile() 方法来创建新文件到指定路径。
注意: 如果文件 JavaFile.java 不存在,则只会创建新文件。否则程序返回文件已经存在。

示例 2: 将内容写入文件的 Java 程序

在 Java 中,我们可以使用 FileWriter 类将数据写入文件。在前面的示例中,我们创建了名为 JavaFile.java 的文件。现在让我们写一个程序到这个文件中。
// importing the FileWriter class
import java.io.FileWriter;
class Main {
  public static void main(String args[]) {
    // creates a multiline string using + operator
    // the string is a Java Program
    String program = "class JavaFile { " +
                       "public static void main(String[] args) { " +
                         "System.out.println(\"this is file\");"+
                       "}"+
                     "}";
     try {
       // Creates a Writer using FileWriter
       FileWriter output = new FileWriter("JavaFile.java");
       // Writes the program to file
       output.write(program);
       System.out.println("Data is written to the file.");
       // Closes the writer
       output.close();
     }
     catch (Exception e) {
       e.getStackTrace();
     }
  }
}
在上面的例子中,我们使用了 FileWriter lass 将字符串数据写入文件 Javafile.java
当您运行程序时,文件 JavaFile.java 将包含字符串程序中存在的数据。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4