1. 程式人生 > 實用技巧 >Java IO流 (1)------儲存檔案與讀取檔案

Java IO流 (1)------儲存檔案與讀取檔案

1、寫入讀取封裝步驟

/*
 * 1.寫入
 *  1)指定檔案路徑以及檔名
 *  2)判斷資料夾以及檔案是否存在
 *  3)建立檔案以及資料夾
 *  4)輸出流
 *  5)寫入
 *  6)轉換
 * 2.讀取
 *  1)指定路徑
 *  2)判斷檔案路徑是否存在
 *  3)判斷是否是檔名
 *  4)字元流
 *  5)read出來的是單個單個的字元,用StringBuilder來拼接
 *  6)while迴圈
 * 3.封裝
 *  1)new物件
 *  2)set裝載
*/

2、建立

 1 public static File createNote(String type, String fileName) {
2 //new一個File類,並傳入路徑 3 File file = new File(CommanPath.PATH.getValue()); 4 5 //寫入需要判斷資料夾是否存在,不存在則建立,讀取不需要 6 if (!"read".equals(type)) { 7 //判斷資料夾是否存在,不存在則先建立 8 if (!file.exists()) { 9 file.mkdirs(); 10 } 11 } 12 //在new一個file類,傳入路徑以及檔名 13 File file1 = new
File(CommanPath.PATH.getValue(), fileName); 14 if (!"read".equals(type)) { 15 //判斷檔案是否存在,不存在則先建立 16 try { 17 if (!file1.isFile()) { 18 file1.createNewFile(); 19 } 20 } catch (IOException e) { 21 e.printStackTrace(); 22 }
23 } 24 25 return file1; 26 }

3、寫入

 1 /**
 2  * 寫入
 3  */
 4 private void writeMessage() {
 5     File file = IoUtil.createNote("write", Constant.MESSAGE_NAME);
 6     try {
 7         OutputStream outputStream = new FileOutputStream(file);
 8         IoMessageModel ioMessageModel = new IoMessageModel();
 9         outputStream.write(ioMessageModel.getMessageDescription().getBytes());
10         outputStream.close();
11     } catch (IOException e) {
12         e.printStackTrace();
13     }
14 }

4、讀取

 1 /**
 2  * 讀取記事本
 3  *
 4  * @return 字元流資料
 5  */
 6 public static String readNote(String fileName) {
 7     //找到檔案地址以及檔名
 8     File file = createNote("read", fileName);
 9     /*
10         String 不可變字串,字串拼接時效率低,浪費記憶體
11         StringBuffer 可變字串,執行緒安全,多執行緒操作
12         StringBuilder 可變字串,執行緒不安全,單執行緒操作,速度最快。在操作可變字串時一般用StringBuilder,
13         如果考慮執行緒安全則必須使用StringBuffer
14      */
15     StringBuilder result = new StringBuilder();
16     try {
17         /*
18          * 位元組流,會出現亂碼
19          */
20        /* InputStream inputStream = new FileInputStream(file);
21         int data;
22         while ((data=inputStream.read())>0){
23             System.out.print((char) data);
24         }*/
25         /*
26          * 字元流
27          */
28         Reader reader = new FileReader(file);
29         int data;
30         while ((data = reader.read()) > 0) {
31             result.append((char) data);
32         }
33     } catch (IOException e) {
34         e.printStackTrace();
35     }
36     //將StringBuiler轉換為String
37     return result.toString();
38 }

5、列舉類

 1 /**
 2  * @author liangd
 3  * date 2020-10-13 12:57
 4  * code 列舉類
 5  */
 6 public enum CommanPath {
 7     //識別符號
 8     AA("@#%"),
 9     //定義檔案路徑
10     PATH("E:\\liangd\\note");
11 
12     private String value;
13 
14     //構造方法
15     CommanPath(String value) {
16         this.value = value;
17     }
18 
19     public String getValue() {
20         return value;
21     }
22 }