最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java中使用File類創(chuàng)建文件方法總結(jié)

 更新時(shí)間:2025年05月22日 10:05:45   作者:棐木  
Java File類是I/O操作基礎(chǔ),用于表示文件路徑,提供構(gòu)造方法、文件創(chuàng)建、信息獲?。ㄈ缑Q、路徑、大?。┘澳夸洸僮?這篇文章主要介紹了Java中使用File類創(chuàng)建文件方法的相關(guān)資料,需要的朋友可以參考下

Java 中的 File 類

在 Java 中,文件文件流是處理數(shù)據(jù)輸入/輸出的兩個(gè)核心概念,它們是 Java I/O 操作的基礎(chǔ)。

一、文件(File)

定義

  • 文件是操作系統(tǒng)中的存儲(chǔ)單元,用于持久化保存數(shù)據(jù)(如文本、圖片、二進(jìn)制數(shù)據(jù)等)。
  • 在 Java 中,java.io.File 類(或 Java 7+ 的 java.nio.file.Path)用于表示文件或目錄的抽象路徑。
  • 文件本身不存儲(chǔ)數(shù)據(jù),而是通過(guò)路徑指向磁盤(pán)上的具體數(shù)據(jù)。

二、File 類的介紹

1 創(chuàng)建文件對(duì)象的相關(guān)構(gòu)造器

  • new File(File parent, String child) :將父路徑(字符串形式)和子路徑拼接成一個(gè)完整路徑。自動(dòng)處理路徑分隔符(如 Windows 的 \ 或 Linux 的 /)。

    // 示例1:拼接父路徑和子文件
    String parentDir = "C:/Users/Test";
    String childFile = "data.txt";
    File file = new File(parentDir, childFile);
    //會(huì)在2個(gè)目錄之間自動(dòng)加上'/'或'\'
    System.out.println(file.getPath()); // 輸出: C:\Users\Test\data.txt
    
    // 示例2:拼接多級(jí)目錄
    File dir = new File("src", "main/java/com/example");
    System.out.println(dir.getPath()); // 輸出: src\main\java\com\example
    
  • new File(String pathname) :直接通過(guò)路徑名字符串(絕對(duì)路徑或相對(duì)路徑)創(chuàng)建 File 對(duì)象。路徑可以是文件或目錄。

    // 示例1:使用絕對(duì)路徑
    File file1 = new File("C:/Users/Test/example.txt");
    System.out.println(file1.getPath()); 
    // 輸出: C:\Users\Test\example.txt
    
    // 示例2:使用相對(duì)路徑(相對(duì)于當(dāng)前項(xiàng)目根目錄)
    File file2 = new File("data/config.json");
    System.out.println(file2.getPath()); 
    // 輸出: data\config.json
    
  • new File(File parent, String child) :使用一個(gè)已有的 File 對(duì)象表示父路徑,再拼接子路徑。比字符串拼接更靈活,避免路徑分隔符錯(cuò)誤。

    // 示例1:基于父目錄對(duì)象創(chuàng)建子文件
    File parentDir = new File("C:/Users/Test");
    File childFile = new File(parentDir, "logs/app.log");
    System.out.println(childFile.getPath()); // 輸出: C:\Users\Test\logs\app.log
    
    // 示例2:鏈?zhǔn)狡唇幽夸?
    File baseDir = new File("projects");
    File srcDir = new File(baseDir, "src");
    File mainFile = new File(srcDir, "Main.java");
    System.out.println(mainFile.getPath()); // 輸出: projects\src\Main.java
    
  • new File(URI rui) :通過(guò) URI(統(tǒng)一資源標(biāo)識(shí)符) 創(chuàng)建 File 對(duì)象。URI 格式需符合 file: 協(xié)議(如 file:/C:/test/data.txt)。

    import java.net.URI;
    
    // 示例1:使用URI創(chuàng)建File對(duì)象
    try {
        URI uri = new URI("file:/C:/Users/Test/example.txt");
        File file = new File(uri);
        System.out.println(file.getPath()); 
        // 輸出: C:\Users\Test\example.txt
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    // 示例2:處理空格和特殊字符
    //URI 中的特殊字符(如空格)需用 %20 表示,構(gòu)造方法會(huì)解碼后轉(zhuǎn)換為實(shí)際路徑。
    URI uri2 = URI.create("file:/C:/My%20Documents/report.pdf");
    File file2 = new File(uri2);
    System.out.println(file2.getPath()); 
    // 輸出: C:\My Documents\report.pdf
    

總結(jié)對(duì)比

構(gòu)造方法典型使用場(chǎng)景優(yōu)點(diǎn)
File(String pathname)直接指定完整路徑簡(jiǎn)單直接,適合已知路徑
File(String parent, String child)動(dòng)態(tài)拼接父路徑和子路徑避免手動(dòng)處理路徑分隔符
File(File parent, String child)基于已有的 File 對(duì)象構(gòu)建子路徑支持鏈?zhǔn)讲僮?,路徑更安?/td>
File(URI uri)從 URI 格式創(chuàng)建(如編碼后的路徑)自動(dòng)處理特殊字符和協(xié)議

注意 :File 對(duì)象只是一個(gè)路徑的抽象:創(chuàng)建 File 類對(duì)象,并不會(huì)真的在我們電腦上對(duì)應(yīng)的目錄下面創(chuàng)建文件,如果需要實(shí)際的創(chuàng)建文件需要顯式的調(diào)用。

  • 構(gòu)造 File 對(duì)象(如 new File("a.txt")不會(huì)自動(dòng)創(chuàng)建物理文件,僅表示路徑。
  • 必須通過(guò)顯式調(diào)用 createNewFile() 或其他寫(xiě)入操作(如 FileOutputStream 寫(xiě)入數(shù)據(jù))才能實(shí)際生成文件。

2 createNewFile() 的作用

  • 功能

    • 顯式創(chuàng)建一個(gè)空的文件(僅當(dāng)文件不存在時(shí))。
    • 如果文件已存在,則返回 false,不會(huì)覆蓋原有內(nèi)容。
  • 語(yǔ)法

File file = new File("example.txt");
boolean isCreated = file.createNewFile(); // 返回 true 表示創(chuàng)建成功
  • 注意事項(xiàng):
  • 需要處理 IOException

    • 如果父目錄不存在或沒(méi)有寫(xiě)入權(quán)限,會(huì)拋出異常。

    • 必須用 try-catch 包裹或聲明 throws

      import java.io.File;
      import java.io.IOException;
      
      public class CreateFileDemo {
          public static void main(String[] args) {
              File file = new File("test.txt");
              try {
                  if (file.createNewFile()) {
                      System.out.println("文件創(chuàng)建成功");
                  } else {
                      System.out.println("文件已存在");
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      
  • 父目錄必須存在

    • 如果路徑中的父目錄不存在,createNewFile() 會(huì)失敗。

    • 需先調(diào)用 file.getParentFile().mkdirs() 創(chuàng)建父目錄:

      File file = new File("nonexistent_dir/data.txt");
      //File 對(duì)象僅表示路徑,不檢查文件是否存在!需通過(guò) exists() 方法驗(yàn)證。
      if (!file.getParentFile().exists()) {
          file.getParentFile().mkdirs(); // 創(chuàng)建所有缺失的父目錄
      }
      file.createNewFile();
      

3 獲取文件相關(guān)信息的常用方法

  • getName()
    • 作用:返回文件或目錄的名稱(不包含路徑)。
    • 示例:路徑為C:/test/file.txt時(shí),返回file.txt;若為目錄C:/test,返回test
  • getAbsolutePath()
    • 作用:返回文件或目錄的絕對(duì)路徑字符串。
    • 注意:無(wú)論File對(duì)象是相對(duì)路徑還是絕對(duì)路徑創(chuàng)建,均解析為完整路徑。例如,相對(duì)路徑file.txt可能返回/home/user/file.txt。
  • getParent()
    • 作用:返回父目錄的路徑(字符串形式)。若無(wú)父目錄(如根目錄或單文件相對(duì)路徑),則返回null。
    • 示例:路徑為C:/test/file.txt時(shí),返回C:/test;路徑為file.txt時(shí),返回null。
  • length()
    • 作用:返回文件的字節(jié)大小。若文件不存在或?yàn)槟夸?,通常返?code>0L。
    • 注意:需先通過(guò)exists()isFile()驗(yàn)證目標(biāo)是否為有效文件。
  • exists()
    • 作用:檢查文件或目錄是否存在,返回布爾值。
    • 注意:可能受權(quán)限限制影響(如無(wú)訪問(wèn)權(quán)限時(shí)返回false)。
  • isFile()
    • 作用:判斷是否為標(biāo)準(zhǔn)文件(非目錄或符號(hào)鏈接),返回布爾值。
    • 注意:若路徑不存在,返回false
  • isDirectory()
    • 作用:判斷是否為目錄,返回布爾值。
    • 注意:若路徑不存在,返回false。
import java.io.File;
import java.io.IOException;

public class Example {
    public static void main(String[] args) {
        read();
    }
    public static void read() {
        //1.getName()
        //路徑指向文件
        File file1 = new File("D:/0.學(xué)習(xí)/File_Test/read.txt");
        System.out.println(file1.getName());// 輸出 read.txt
        //路徑為目錄
        File file2 = new File("D:/0.學(xué)習(xí)/File_Test");
        System.out.println(file2.getName());// 輸出 File_Test

        //2.getAbsolutePath()
        //以絕對(duì)路徑創(chuàng)建 File 對(duì)象
        File file3 = new File("D:/0.學(xué)習(xí)/File_Test/read3.txt");
        //輸出 D:/0.學(xué)習(xí)/File_Test/read3.txt
        System.out.println(file3.getAbsolutePath());
        //以相對(duì)路徑創(chuàng)建 File 對(duì)象
        File file4 = new File("read4.txt");
        //輸出絕對(duì)路徑 D:\0.學(xué)習(xí)\java筆記\java_Code\TankGame\read4.txt
        System.out.println(file4.getAbsolutePath());

        //3.getParent()
        //File file3 = new File("D:/0.學(xué)習(xí)/File_Test/read3.txt");
        //輸出 D:\0.學(xué)習(xí)\File_Test
        System.out.println(file3.getParent());
        //根目錄或單文件相對(duì)路徑,返回 null
        File file5 = new File("D:");
        System.out.println(file5.getParent());//null

        //4.length()
        File file6 = new File("D:/0.學(xué)習(xí)/File_Test/read6.txt");
        System.out.println(file6.length());
        try {
            file6.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(file6.length());
    }
}

4 目錄的操作和文件的刪除

1. mkdir()

  • 作用 :創(chuàng)建單層目錄(僅當(dāng)父目錄存在時(shí)才能成功)。
  • 返回值 :boolean:目錄創(chuàng)建成功返回 true,失敗返回 false。
  • 適用場(chǎng)景 :當(dāng)明確知道父目錄已經(jīng)存在時(shí),直接創(chuàng)建子目錄。

2. mkdirs()

  • 作用 :創(chuàng)建多層目錄(自動(dòng)創(chuàng)建路徑中所有不存在的父目錄)。
  • 返回值 :boolean:所有目錄創(chuàng)建成功返回 true,失敗返回 false
  • 適用場(chǎng)景 :不確定父目錄是否存在時(shí),直接創(chuàng)建完整路徑。

3. delete()

  • 作用 :刪除文件或空目錄(非空目錄無(wú)法刪除)。
  • 返回值 :boolean:刪除成功返回 true,失敗返回 false。
  • 適用場(chǎng)景 :刪除文件或空目錄。
import java.io.File;
import java.io.IOException;

public class Example {
    public static void main(String[] args) {
        dir();
    }
    public static void dir() {
        //1.mkdir() 創(chuàng)建單層目錄
        File file1 = new File("D:/0.學(xué)習(xí)/File_Test/demo1");
        //要求父目錄必須存在,否則無(wú)法創(chuàng)建成功
        //即,D:/0.學(xué)習(xí)/File_Test 必須存在才能成功創(chuàng)建 demo1 目錄
        boolean mkdir = file1.mkdir();
        if(mkdir) {
            System.out.println("創(chuàng)建成功");
        } else {
            System.out.println("創(chuàng)建失敗");
        }

        //2.mkdirs() 創(chuàng)建多層目錄
        File file2 = new File("D:/0.學(xué)習(xí)/File_Test/demo2");
        //如果路徑中有不存在的自動(dòng)創(chuàng)建
        boolean mkdirs = file2.mkdirs();

        //3.delete() 刪除文件或空目錄(非空目錄無(wú)法刪除)
        //刪除 demo2 空目錄
        boolean delete = file2.delete();
        File file3 = new File("D:/0.學(xué)習(xí)/File_Test/demo1/dir.txt");
        try {
            file3.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //刪除 dir.txt 文件
        file3.delete();
    }
}

總結(jié) 

到此這篇關(guān)于Java中使用File類創(chuàng)建文件方法的文章就介紹到這了,更多相關(guān)Java用File類創(chuàng)建文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

常宁市| 瑞昌市| 中山市| 阳西县| 叶城县| 建平县| 南和县| 卢龙县| 中宁县| 嵊州市| 新宾| 凌源市| 东乌珠穆沁旗| 长汀县| 伊川县| 乌兰浩特市| 乌鲁木齐县| 梁山县| 涡阳县| 南郑县| 乌拉特后旗| 当涂县| 毕节市| 嫩江县| 扎兰屯市| 金山区| 平阳县| 桂阳县| 洛宁县| 闽清县| 扎鲁特旗| 长治县| 寿光市| 海门市| 汽车| 新和县| 大足县| 收藏| 保康县| 电白县| 宣威市|