2020杭電多校第八場部分題解(1003/1006/1008)
阿新 • • 發佈:2020-08-13
File和IO流概述:
File類:
- 可以將File理解為檔案或者資料夾的路徑
- File封裝的並不是一個真正的檔案
- 它僅僅是一個路徑名,可以存在,也可以不存在
File類的構造方法:
絕對路徑和相對路徑:
File類的建立功能:
File file =new File("路徑");
- file.creatNewFile(); 建立一個新檔案
- file.mkdir();建立單級資料夾
- file.mkdirs();建立多級資料夾
File類的刪除功能:
檔案直接刪,資料夾需為空
File類的獲取和判斷方法:
File file=new File("路徑");
File類的判斷方法:
file.isDirectory();判斷是否是資料夾
file.isFile();判斷是否是檔案
file.exists();判斷檔案是否存在
File類的獲取方法:
file.getAbsoPath();獲取絕對路徑
file.getPath();獲取構造方法中的路徑
file.getName();獲取檔案或資料夾的名稱
File的listFiles方法:
進入不了則為null
刪除多級資料夾:
以桌面考試資料夾為例(反正我也不想要裡面的東西了)
這是裡面的目錄:
刪除遞迴程式碼如下:
1 public class TestDelete { 2 public staticvoid main(String[] args) { 3 File file = new File("C:\\Users\\ZYH\\Desktop\\考試"); 4 Mydelete(file); 5 } 6 private static void Mydelete(File file) { 7 //獲取刪除資料夾file集合 8 File[] files = file.listFiles(); 9 //增強for遍歷: 10 for (File file1 : files) {11 //判斷 12 if (file1.isFile()) { 13 file1.delete(); 14 } else { 15 Mydelete(file1); 16 } 17 } 18 file.delete(); 19 } 20 21 22 }
案例:統計一個資料夾中每種檔案的個數並列印:
思路:
程式碼如下:
1 public class CuntFile { 2 public static void main(String[] args) { 3 File file = new File("C:\\Users\\ZYH\\Desktop\\檔案\\基礎題目"); 4 HashMap<String, Integer> hashMap = new HashMap<>(); 5 theCount(file, hashMap); 6 System.out.println(hashMap); 7 8 9 } 10 11 private static void theCount(File file, HashMap<String, Integer> hashMap) { 12 13 File[] files = file.listFiles(); 14 for (File file1 : files) { 15 if (file1.isFile()) { 16 String name = file1.getName(); 17 18 String[] split = name.split("\\."); 19 20 String s = split[1]; 21 Set<String> set = hashMap.keySet(); 22 if (!set.contains(s)) { 23 hashMap.put(s, 1); 24 25 26 } else { 27 Integer s1 = hashMap.get(s); 28 s1 += 1; 29 hashMap.put(s, s1); 30 31 32 } 33 } else { 34 theCount(file1, hashMap); 35 36 } 37 38 } 39 40 41 } 42 }
IO流的分類:
位元組流:
位元組輸出流FileOutputStream:
注意事項:
- 如果目的地指向的檔案不存在,會自動幫我們建立
- 如果存在會清空,再進行寫入資料(加true後不清空)
- 通過IO流操作檔案後,必須關流釋放資源,否則檔案會一直被佔用
位元組流寫資料的三種方式:
- write(int b); 一次寫一個位元組資料
- write(byte[]arr) 一次寫一個位元組陣列
- write(byte[]arr,int index,int len) 一次寫陣列的指定部分
如何換行和續寫:
位元組輸入流FileInputStream:
位元組流賦值檔案模板:
1 public class read { 2 public static void main(String[] args) throws IOException { 3 FileInputStream fis = new FileInputStream("day10\\a.txt"); 4 FileOutputStream fos = new FileOutputStream("day10\\a1.txt"); 5 byte[] bytes = new byte[1024]; 6 int len; 7 while ((len = fis.read(bytes)) != -1) { 8 fos.write(bytes, 0, len); 9 } 10 fis.close(); 11 fos.close(); 12 13 14 } 15 }
複製檔案就用位元組流
位元組緩衝流:
- BufferOutputStream 位元組緩衝輸出流
- BufferInputStream 位元組緩衝輸入流
緩衝流使用位元組流的方法
緩衝流是通過定義一個8192位元組長度的陣列來實現緩衝區
字元流(位元組流+編碼表)
- FileWrite字元寫出流
- FileRedar字元寫入流
字元流編碼表:
字元流有五種方法:
字元流寫資料注意事項:
字元流flush和close方法
字元流讀資料的兩種方法:
字元緩衝流
字元緩衝輸入流:
BufferReader(傳參用FileReader)
字元緩衝輸出流:
BufferWriter(傳參用FileWriter)
字元緩衝流特有的方法:
從硬碟到記憶體或者從記憶體到硬碟用字元流。
IO流小結: