java緩衝流複製文件

  • 字節緩衝

  public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src\\1.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src\\1_copy.jpg"));
        int len=0;
        byte[] bytes = new byte[1024];
        while((len =bis.read(bytes))!=-1){
            bos.write(bytes,0,len);
        }
        bos.close();
        bis.close();

        long end = System.currentTimeMillis();
        System.out.println("共耗時:"+(end-start)+"s");
    }
  • 字符緩衝

  對於中文,一個字符因爲編碼不一樣可能等於兩個字節,也有可能等於三個字節。字符流解決了中文轉換的亂碼問題。編碼

        long start = System.currentTimeMillis();
        BufferedReader br = new BufferedReader(new FileReader("src\\buffer2.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("src\\buffer2_copy.txt"));
        String line ;
        while((line=br.readLine())!=null){
            System.out.println(line);
            bw.write(line);
            bw.newLine();
        }
        bw.flush();
        bw.close();
        br.close();
        long end = System.currentTimeMillis();
        System.out.println("共耗時:"+(end-start)+"s");
    }
相關文章
相關標籤/搜索