java io重新導向

來源:互聯網
上載者:User
翻譯:Cherami
email:cherami@163.net 
原文:http://developer.java.sun.com/developer/TechTips/2000/tt0815.html


如果你經常使用UNIX 或者 Windows shells (命令處理器),你可能經常像這樣使用I/O重新導向:
    $ command >outfile
這個用法是說:運行一個命令,並將它的標準輸出 (例如System.out.println的輸出)定向到指定的檔案而不是輸出到控制台或者螢幕。
這個特性非常有用。在java程式中也可以達到這個目的而不用依賴與shell。通常情況下如果你使用的編程風格依賴於標準輸入輸出 (就像UNIX shell 和其它工具包那樣), 你可能不需要或者不想在程式裡面重新導向。但是有時候你希望這樣,讓我們看幾個範例。 
第一個範例重新導向標準輸出到一個檔案:
    import java.io.*;
    public class RedirectDemo1 {
        public static void main(String args[]) throws IOException {
            // 在檔案上建立一個PrintStream 
            FileOutputStream fos =
                new FileOutputStream("out.txt");
            BufferedOutputStream bos =
                new BufferedOutputStream(fos, 1024);
            PrintStream ps =
                new PrintStream(bos, false);
            // 重新導向System.out 到該檔案
            System.setOut(ps);
            // 輸出
            System.out.println("This is a test/u4321");
            int n = 37;
            System.out.println("The square of " + n +
                " is " + (n * n));
            ps.close();
        }
    }

標準輸出 (System.out) 是PrintStream 對象的一個引用。為了重新導向輸出,建立一個這樣的對象來表示一個檔案或者其它的輸出資料流 (例如一個網路連接)。然後使用System.setOut 調用改變System.out 引用。
JDK 1.3 中實現的java.lang.System 代碼是這樣的形式: 
    FileOutputStream fdOut =
        new FileOutputStream(FileDescriptor.out);
    setOut0(new PrintStream(
        new BufferedOutputStream(fdOut, 128), true));
這個代碼初始化System.out。因此,在預設情況下,System.out 是一個PrintStream,該 PrintStream 是從FileDescriptor.out 建立的一個FileOutputStream 檔案,帶有128位元組的緩衝區,自動重新整理(遇到新行符或者位元組向量時自動輸出)。當輸出像上面那樣被重新導向,System.out 變成使用System.setOut傳遞進來的一個新建立的PrintStream 對象的引用。
RedirectDemo1 有幾個問題,首先是PrintStream 使用平台預設的字元編碼將字元轉換為位元組。這通常是好事,例如,如果你的小程式中有這樣一行:
    System.out.println("this is a test");
而且你在美國這樣運行程式:
    $ java prog >outfile
程式在檔案"outfile"中存入ASCII字元。這可能是你想要的得到的7位的ASCII文字檔。
但是程式中如果有Unicode字元'/u4321',它將被轉換為一個'?' 。如果你查看檔案你可以看到?。換句話說,預設的編碼沒有正確的處理那個輸出字元。
另一個問題是I/O 重新導向可以被推廣,例如你能將輸出定向到一個字串而不是一個檔案。這裡有一個範例包括了上面的兩個問題:
    import java.io.*;
    public class RedirectDemo2 {
        public static void main(String args[]) throws IOException {
            // 在StringWriter 上建立一個PrintWriter。
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            // 輸出一些東西到StringWriter
            pw.println("This is a test/u4321");
            int n = 37;
            pw.println("The square of " + n + " is " + (n * n));
            // 得到被寫入的字串
            String str = sw.toString();
            // 顯式它
            System.out.print(str);
            // 將字串輸出到檔案,使用 UTF-8 編碼
            FileOutputStream fos =
                new FileOutputStream("out.txt");
            OutputStreamWriter osw =
                new OutputStreamWriter(fos, "UTF-8");
            BufferedWriter bw =
                new BufferedWriter(osw);
            bw.write(str);
            bw.close();
            // 讀回字串並檢查
            FileInputStream fis =
                new FileInputStream("out.txt");
            InputStreamReader isr =
                new InputStreamReader(fis, "UTF-8");
            BufferedReader br =
                new BufferedReader(isr);
            String s1 = br.readLine();
            String s2 = br.readLine();
            br.close();
            String linesep = System.getProperty("line.separator");
            if (!str.equals(s1 + linesep + s2 + linesep))
                System.err.println("equals check failed");
        }
    }

範例的第一部分在一個StringWriter 上建立一個PrintWriter對象,它和PrintStream 類似,但是操作的是字元而不是位元組流。StringWriter 用於向一個動態內部緩衝區聚集字元,以後恢複為一個String或者StringBuffer。
在輸出被寫入StringWriter 後,聚集的字串恢複了,然後字串使用OutputStreamWriter和 UTF-8編碼被寫入檔案。這個編碼在所有的java實現中都被支援。它將'/u0001' 到 '/u007f'範圍內的字元編碼為一個位元組而其它字元為兩個或者三個位元組。
最後,字串從檔案讀回,還是使用UTF-8 編碼。然後和原始的字串比較。原始的字串內有兩個行分隔字元,因此讀回的是兩個字串,為了比較而添加了行分隔字元。
注意你也可以從一個檔案或者字串重新導向輸入,使用一個像StringReader這樣的類。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.