Java 創建文件三種方法

1. File.createNewFile() 方法

  1. 可以通過 java.io.FilecreateNewFile() 方法創建;返回可能是true或者false 或者拋出 IOException
  2. 生成File對象指定的參數如 實例所示 Test3 中演示的三種情況,1、 2、3 對應 ,絕對路徑、只提供文件名稱或者相對路徑,但是路徑中的文件夾必須是已經存在的;例如3 所示如果沒有tmp文件夾存在,則會拋出異常
Exception in thread "main" java.io.IOException: 系統找不到指定的路徑。
   at java.io.WinNTFileSystem.createFileExclusively(Native Method)
   at java.io.File.createNewFile(File.java:1012)
   at com.malone.hello.io.Test3.main(Test3.java:34)
public class Test3 {
    /**
     *  演示在Java中怎麼樣創建文件
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // 獲取文件分隔符
        String fileSeparator = System.getProperty("file.separator");
        // https://www.cnblogs.com/brucemengbm/p/7094039.html 獲取各種系統信息
        String home = System.getProperty("user.home");
        // 1 絕對路徑 
        String absoluteFilePath = home+fileSeparator+"file.txt";
        File file = new File(absoluteFilePath);
        if(file.createNewFile()){
            System.out.println(absoluteFilePath+" 創建成功");
        }else System.out.println("文件 "+absoluteFilePath+" 已經存在");

        // 2 只提供文件名
        file = new File("file.txt");
        if(file.createNewFile()){
            System.out.println("file.txt 創建成功,在工程根目錄");
        }else System.out.println("文件 file.txt 在工程根目錄已經存在");

        // 3 相對路徑
        String relativePath = "tmp"+fileSeparator+"file.txt";
        file = new File(relativePath);
        if(file.createNewFile()){
            System.out.println(relativePath+" 文件在工程根目錄創建工程");
        }else System.out.println("文件 "+relativePath+" 在工程根目錄已經存在");
    }
}

FileOutputStream.write(byte[] b) 方法

創建文件並且同事寫入內容,文件路徑的指定同上一個例子

public class Test4 {
    public static void main(String[] args) throws Exception {
        String fileData = "malone";
        FileOutputStream fos = new FileOutputStream("name.txt");
        fos.write(fileData.getBytes());
        fos.flush();
        fos.close();
    }
}

Java NIO Files.write() 方法

我們可以使用NIO 的File類常見文件並且寫入內容;這個方法我們不用關心關閉IO資源

public class Test5 {
    public static void main(String[] args) throws IOException {
        String fileData = "文件創建 - Nio";
        Files.write(Paths.get("文件創建 - Nio.txt"), fileData.getBytes());
    }
}

參考

  • https://www.journaldev.com/825/java-create-new-file
  • https://www.cnblogs.com/brucemengbm/p/7094039.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章