1. 程式人生 > >IO流 檔案注意四點

IO流 檔案注意四點

IO流 檔案注意四點

1、快取小,快取就是每次給流分配陣列大小,快取可以看做是一輛一輛卡車運輸貨物。byte[1024] = 1kb;
2、每次快取讀多少,寫入到磁碟就多少,不要有空的寫入。
3、快取完了之後需要強制flush到磁碟
4、一定要關閉流:關閉流可以在try裡面,也可以在finally裡面關閉
package javacore;

import java.io.*;

/**
 * @author lixw
 * @date created in 22:10 2018/12/17
 */
public class FileReader {
    public static
void main(String[] args) { //readText(); // writeTxt(); long start = System.currentTimeMillis(); String source = "F:\\BaiduNetdiskDownload\\video\\01課程回顧__rec.avi"; String target = "F:\\BaiduNetdiskDownload\\video\\01課程回顧__rec_copy.avi"; try(InputStream is =
new FileInputStream(source); OutputStream os = new FileOutputStream(target)) { System.out.println(is.available()/1024/1024); //8G -> 6G //1.快取要小(相對磁碟) byte[] buff = new byte[1024 * 512]; int len = 0; while ((len = is.read
(buff)) != -1){ //2.讀多少 寫多少 os.write(buff,0,len); } //3.flush到磁碟 os.flush(); } catch (IOException e) { e.printStackTrace(); } System.out.println(System.currentTimeMillis() - start); } private static void writeTxt() { //字元流 String target = "C:\\Users\\li\\Desktop\\ArrayTest.java"; BufferedWriter writer = null; FileWriter fw = null; try { fw = new FileWriter(target); writer = new BufferedWriter(fw); writer.append("222"); //記憶體中重新整理到磁碟 writer.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if (fw!=null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } if (writer!=null){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static void readText() { InputStream is = null; String filePath = "D:\\eclipse x64\\mymaven\\src\\main\\java\\javacore\\ArrayTest.java"; //包裝類 BufferedReader reader = null; java.io.FileReader fileReader = null; try { fileReader = new java.io.FileReader(filePath); reader = new BufferedReader(fileReader); String s = reader.readLine(); while (s != null){ System.out.println(s); s = reader.readLine(); } } catch (IOException e) { e.printStackTrace(); }finally { //!!!使用之後關閉流 //關閉之前先判空 if (fileReader!=null){ try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (reader !=null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }