2015年10月7日 星期三

InputStream 與 OutputStream

Byte 種類的 I/O 處理:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class StreamDemo {
    public static void main(String[] args){
        byte[] data = new byte[128];
        int dataLen = data.length;
        
        try(FileInputStream fis = new FileInputStream(args[0]);
            FileOutputStream fos = new FileOutputStream(args[1])){
            System.out.println("Bytes available: " + fis.available());
            int count = 0;
            int read = 0;
            while ((read = fis.read(data)) != -1){
                if (read < dataLen) 
                    fos.write(data,0,read);
                else
                    fos.write(data);
                count += read;
            }
            System.out.println("Wrote: " + count);
        }   catch (FileNotFoundException ex) {
            System.out.println("File not Found! " + ex);
        } catch (IOException ex) {
            System.out.println("I/O Error! " + ex);
        }
    }
}