Java 示例 - 创建新文件

  • 问题描述

    如何创建一个新文件?
  • 解决方案

    此示例演示了使用 File() 构造函数和 File 类的 file.createNewFile() 方法创建新文件的方法。
    
    import java.io.File;
    import java.io.IOException;
    public class Main {
       public static void main(String[] args) {
          try {
             File file = new File("C:/myfile.txt");
             
             if(file.createNewFile())System.out.println("Success!");
             else System.out.println ("Error, file already exists.");
          }
          catch(IOException ioe) {
             ioe.printStackTrace();
          }
       }
    }
    
  • 结果

    上面的代码示例会产生如下结果(如果“myfile.txt之前不存在)
    
    Success!
    
    下面是另一个文件创建示例
    
    import java.io.IOException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    import java.util.Arrays;
    import java.util.List;
    public class JavaApplication1 { 
       public static void main(String[] args) throws IOException {
          createFileUsingFileClass();
          createFileUsingFileOutputStreamClass();
          createFileIn_NIO();
          // TODO code application logic here
       } 
       private static void createFileUsingFileClass() throws IOException { 
          File file = new File("c://testFile1.txt");
          
          //Create the file
          if (file.createNewFile()) { 
             System.out.println("File is created!");
          } else {
             System.out.println("File already exists.");
          } 
          
          //Write Content
          FileWriter writer = new FileWriter(file);
          writer.write("Test data");
          writer.close();
       } 
       private static void createFileUsingFileOutputStreamClass() throws IOException { 
          String data = "Test data";
          FileOutputStream out = new FileOutputStream("c://testFile2.txt");
          out.write(data.getBytes());
          out.close();
       } 
       private static void createFileIn_NIO()  throws IOException { 
          String data = "Test data";
          Files.write(Paths.get("c://testFile3.txt"), data.getBytes());
          List<String> lines = Arrays.asList("1st line", "2nd line");
          Files.write(Paths.get(
             "file6.txt"), lines, StandardCharsets.UTF_8, 
             StandardOpenOption.CREATE, StandardOpenOption.APPEND);
       }
    }