Chin-Yi Tsai cyt@pmlab.iecs.fcu.edu.tw http://140.134.26.25/~cyt Java Chin-Yi Tsai cyt@pmlab.iecs.fcu.edu.tw http://140.134.26.25/~cyt
Outline Java I/O Stream
import java.io.*; import java.io.*; Object File InputStream File RandomAccessFile OutputStream Reader Wrtier ByteArrayInputStream StringBufferInputStream FileInputStream SequenceInputStream FilterInputStream PipedInputStream ObjectInputStream ByteArrayOutputStream StringBufferOutputStream FileOutputStream SequenceOutputStream FilterOutputStream PipedOutputStream ObjectOutputStream BufferedInputStream DataInputStream LineNumberInputStream PushbackInputStream BufferedOutputStream DataOutputStream PrintStream BufferedWriter StringWriter CharArrayWriter PrintWriter FilterWriter PipedWriter OutputStreamWriter FileWriter BufferedReader StringReader CharArrayReader FilterReader PipedReader InputStreamReader FileReader Stream是一個通化的概念,java.io package支援stream import java.io.*;
指定輸入源(從別人家接水管到我家,接水) 指定輸出地(從我家接水管到別人家,送水) Stream的概念 stream是資料輸入及輸出的通道 從資料來源讀取資料的input stream 將資料寫出到目的地的output stream input stream(輸入水管): 指定輸入源(從別人家接水管到我家,接水) output stream(輸出水管): 指定輸出地(從我家接水管到別人家,送水)
輸入源 輸出地 inputStream OutputStream
I/O 字元 Writer Reader 位元組 InputStream OutputStream InputStreamReader BufferedWriter CharArrayWriter FilterWriter PipedWriter StringWriter BufferedReader CharArrayReader FilterReader PipedReader StringReader 位元組 InputStream OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream ObjectOutputStream PipedOutputStream ByteArrayInputStream FileIntputStream FilterIntputStream ObjectIntputStream PipedIntputStream InputStreamReader OutputStreamWriter
以byte為讀取單位的輸入通道 (程式拿byte的水杯來接水) InputStream 以byte為讀取單位的輸入通道 (程式拿byte的水杯來接水) OutputStream 以byte為單位的輸出通道 (程式拿byte的水杯來送水) Reader 以兩個byte(character)為讀取單位的輸入通道 Writer 以兩個byte(character)為單位的輸出通道
為什麼要2個byte? 以兩個byte為讀寫單位的輸出及輸入通道主要是 用以讀寫以Unicode或亞洲文字編碼的資料。
Java I/O 作用 FileInputStream FileOutputStream InputStream OutputStream 讀取及寫入檔案 網路通訊 過濾資料 加/解 密 壓/解壓 縮 在thread之間傳送資料 把物件寫入串流 檔案和目錄之操作 讓user中GUI介面選取檔案 Java所有I/O動作都是以串流為基礎 FilterInputStream FilterOutputStream PipedInputStream PipedOutputStream ObjectInputStream ObjectOutputStream File
Stream 操作 程式 File2_out OutputStream write InputStream read File1_in
各種分類 InputStream OutputStream Reader Writer File Byte位元組 Char字元 ---表示其子類別有各自不同的型態運用 BufferedWriter CharArrayWriter FilterWriter PipedWriter StringWriter 不同的用途
不同種類的串流 輸入串流 記憶中的串流 輸出串流 壓縮串流 檔案串流 密文串流 網路串流 物件串流 濾器串流 Reader 資料串流 Writer
I/O 字元 Writer Reader 位元組 InputStream OutputStream InputStreamReader BufferedWriter CharArrayWriter FilterWriter PipedWriter StringWriter BufferedReader CharArrayReader FilterReader PipedReader StringReader 位元組 InputStream OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream ObjectOutputStream PipedOutputStream ByteArrayInputStream FileIntputStream FilterIntputStream ObjectIntputStream PipedIntputStream 資料串流 記憶中的串流 壓縮串流 密文串流 物件串列化 InputStreamReader OutputStreamWriter
標準輸入 標準輸出 錯誤輸出 InputStream stdin = System.in; 鍵盤 InputStream stdin = System.in; OutputStream stdout = System.out; OutputStream stderr = System.err; 螢幕 (錯誤訊息) 螢幕
InputStream InputStreamReader Reader InputStream BufferedReader InputStreamReader converter=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(converter); Reader BufferedReader InputStreamReader InputStream
過濾串流 Super class FilterInputStream FilterOutputStream FilterReader FilterWriter
java.io.File File f = new File(“/temp/file.txt”); File f = new File(“/temp/temp2”); File f = new File(“/tmep”,”fiel.txt”); File tempDir = new File(“/temp”); File f = new File(tempDir,”file.txt”)
InputStream InputStream stdin=System.in; import java.io.*; public class StreamPrinter{ InputStream myInput; public static void main(String[] args){ myInput=System.in; try{ while(true){ int datum=myInput.read(); if(datum==-1) break; System.out.println(datum); } }catch(IOException e){ }
OutputStream OutputStream stdout=System.out; import java.io.*; public class AsciiChart{ public static void main(String[] args){ for(int i=32;i<127;i++){ System.out.write(i); if(i%8==7) System.out.write(‘\n’); else System.out.write(‘\t’); }
Break
File Stream FileInputStream FileOutputStream
import java.io.*; public class FileCopier{ public static void main(String[] args){ if(args.length!=2){ System.err.println(“Usage:java FileCopier infile outfile”); } try{ FileInputStream fin=null; FileOutputStream fout=null; fin=new FileInputStream(args[0]); fout=new FileOutputStream(args[1]); byte[] buffer=new byte[256]; while(true){ int byteRead=fin.read(buffer); if(byteRead==-1) break; fout.write(buffer,0,byteRead); }catch(IOException e){} fin.close(); fout.close();
Network Stream Stream source URL,URLConnection, Socket,ServerSocket
URL try{ URL u=new URL(http://www.fcu.edu.tw/); InputStream in=u.openStream(); int b; while((b=in.read())!=-1){ System.out.write(b); } catch(MalformedURLException e){ System.err.println(e); catch(IOException e){
URLConnection try{ URL u=new URL(http://www.fcu.edu.tw/); URLConnection uc=u.getCOnnection(); uc.connect(); InputStream in=uc.getInputStream(); } catch(IOException e){ System.err.println(e);
Socket Socket s=new Socket(host,80); String request=“my Request”; byte[] b=request.getBytes(); OutputStream out=s.getOutputStream(); InputStream in=s.getInputStream(); out.write(b); out.flush();
ServerSocket try{ ServerSocket ss=new ServerSocket(80); while(true){ Socket s=ss.accept(); OutputStream out=s.getOutputStream(); … s.close(); } catch(IOException e){ System.err.println(e);
Filter Stream Source encryption Filter compression translation Destination
資料壓縮 Java.util.zip GZIPOutputStream GZIPInputStream GZIP,ZIP source
GZIPOutputStream import java.io.*; import java.util.zip.*; public class GZip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GZip source"); } String zipname = args[0] + ".gz"; GZIPOutputStream zipout; try { FileOutputStream out = new FileOutputStream(zipname); zipout = new GZIPOutputStream(out); }catch (IOException e) { System.out.println("Couldn't create " + zipname + "."); byte[] buffer = new byte[sChunk]; FileInputStream in = new FileInputStream(args[0]); int length; while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length); in.close( ); catch (IOException e) { System.out.println("Couldn't compress " + args[0] + "."); zipout.close( ); } catch (IOException e) {}
GZIPInputStream FileInputStream in=new FileInputStream(zipname); Zipin=new GZIPInputStream(in); FileOutputStream out=new FileOutputStream(source); Int length; While((length=zipin.read(buffer,0,sChunk))!=-1) out.write(buffer,0,length); out.close();
記憶體中的Stream Sequence input stream byte array stream Piped I/O stream 將幾個輸入串流串聯起來,讓它們看起來像單一串流 byte array stream 可以把輸出放在位元組陣列,並從位元組陣列讀取輸入 Piped I/O stream 可以讓thread的輸出成為另一個thread的輸入
Piped I/O Stream Thread1 Thread2 PipedInputStream PipedOutputStream PipedOutputStream pout=new PipedOutputStream(); PipedInputStream pin=new pipedInputStream(pout); FibonacciWriter fw=new FibonacciWriter(pout,howMany); FibonacciReader fr=new FibonacciReader(pin); fw.start(); fr.start(); Thread1 PipedInputStream Thread2 PipedOutputStream
Object File 檔案作業 Reader Wrtier ByteArrayInputStream RandomAccessFile OutputStream Reader Wrtier ByteArrayInputStream StringBufferInputStream FileInputStream SequenceInputStream FilterInputStream PipedInputStream ObjectInputStream ByteArrayOutputStream StringBufferOutputStream FileOutputStream SequenceOutputStream FilterOutputStream PipedOutputStream ObjectOutputStream BufferedInputStream DataInputStream LineNumberInputStream PushbackInputStream BufferedOutputStream DataOutputStream PrintStream BufferedWriter StringWriter CharArrayWriter PrintWriter FilterWriter PipedWriter OutputStreamWriter FileWriter BufferedReader StringReader CharArrayReader FilterReader PipedReader InputStreamReader FileReader 檔案作業
檔案作業(java.io.File) boolean canRead()---此目錄或檔案是否可讀? import java.io.*; class ExFile { public static void main ( String args[] ) throws Exception { File myFile = new File( args[0] ); if ( !myFile.exists() || !myFile.canRead( ) ) { System.out.println( "Can't read " + myFile ); return; } if ( myFile.isDirectory( ) ) { String [] files = myFile.list( ); for (int i=0; i< files.length; i++) System.out.println( files[i] ); else try { FileReader fr = new FileReader ( myFile ); BufferedReader in = new BufferedReader( fr ); String line; while ((line = in.readLine( )) != null) System.out.println(line); System.out.println(myFile+"'s length="+myFile.length()); catch ( FileNotFoundException e ) { System.out.println( "File Disappeared" ); 檔案作業(java.io.File) boolean canRead()---此目錄或檔案是否可讀? boolean canWrite() ---此目錄或檔案是否可寫? boolean exists() ---此目錄或檔案是否存在? boolean isFile() ---是否為檔案? boolean isDirectory() ---是否為目錄? boolean isAbsolute()--是否為絶對路徑? String getAbsolutePath()—取得絶對路徑 String getName()--取得檔案或目錄的名稱 String getPath()--取得檔案或目錄的路徑 String length()--取得檔案長度 long lastModified()--取得檔案或目錄的最後修正時間 String[] list()--取得目錄下的檔案列表
Reader and Writer Reader 各種編碼方式 Java本身字元集 (如ASCII…) Writer 以Unicode字元為基準,藉以轉換各種不同的字元集
OutputStreamWriter InputStreamReader 編碼方式: ASCII加希臘文 Writer and Reader抽象類別 FileOutputStream fos=new FileOutputStream(“book.txt”); OutputStreamWriter bookWriter=new OutputStreamWriter(fos,”8859_7”); String text=“\u03B1\u03C1\u03C4\u03B7”; bookWriter.write(text,0,text.length()); 五個unicode字元 (十個位元組) 255,241,229,244,231五個位元組
import java.io.*; public class ExOSW{ public static void main(String[] args){ String encoding=System.getProperty("file.encoding"); String lineSpearator=System.getProperty("line.separator","\r\n"); OutputStream target=null; try{ target=new FileOutputStream(args[0]); } catch(Exception e){} System.out.println(encoding); OutputStreamWriter osw=null; osw=new OutputStreamWriter(target,encoding); catch(Exception ee){} osw.write("Test"); osw.close(); catch(Exception eee){}
ABC 字元ABC 位元組二 位元組一 import java.io.*; public class ExConverter{ public static void main(String[] args){ if(args.length<2){ System.out.println("usage: java ExConverter infile_encoding outfile_encoding infile outfile"); } try{ File infile=new File(args[2]); File outfile=new File(args[3]); FileInputStream fin=new FileInputStream(infile); FileOutputStream fout=new FileOutputStream(outfile); InputStreamReader isr=new InputStreamReader(fin,args[0]); OutputStreamWriter osw=new OutputStreamWriter(fout,args[1]); while(true){ int c=isr.read(); if(c==-1) break; osw.write(c); } osw.close(); isr.close(); }catch(Exception e){} ABC 位元組一 位元組二 字元ABC