1. 程式人生 > >Java I/O 位元組流練習

Java I/O 位元組流練習

要求:將一個檔案拆分成多個小檔案,然後再將這幾個小檔案合併成原來的檔案。

package cn.hcd.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class IOCopyDemo {
	public static void main(String[
] args) { FileInputStream fis = null; FileOutputStream fos = null; try { Scanner sc = new Scanner(System.in); fis = new FileInputStream("E:/kgc/jixieshou.png"); // fis = new FileInputStream("E:/kgc/憲法.txt"); double d = (double)(fis.available())/1024; String s = String.format("%.1f", d)
; System.out.println("該檔案大小為"+Double.valueOf(s)+"KB"); System.out.println("請問您要分為幾個檔案?"); int num = sc.nextInt(); int size = fis.available()/num; //將一個大檔案複製,並拆分成若干個小檔案 byte [] b = new byte [size]; for(int i=0;i<num;i++){ fis.read(b); File file = new File("F:/KGC/part-"+
i+".png"); // File file = new File("F:/KGC/part-"+i+".txt"); fos = new FileOutputStream(file); //不必用file.createNewFile()建立,這句程式碼本身就會建立檔案 fos.write(b, 0, b.length); } System.out.println("已經將檔案拆分成"+num+"個小檔案"); //將拆分開的幾個小檔案再合成一個大檔案 fos = new FileOutputStream(new File("F:/KGC/jixieshou.png"),true); // fos = new FileOutputStream(new File("F:/KGC/憲法.txt"),true); byte [] bb = new byte[size]; for(int i=0;i<num;i++){ FileInputStream fis2 = new FileInputStream("F:/KGC/part-"+i+".png"); // FileInputStream fis2 = new FileInputStream("F:/KGC/part-"+i+".txt"); int len; while((len = fis2.read(bb)) != -1){ fos.write(bb, 0, len); } } System.out.println("已經將"+num+"個小檔案"+"合成了一個檔案"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { fis.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }