1

的FileDescriptor的靜態成員在FileDescriptor.java的源代碼中使用時,我們有以下靜態變量:的FileInputStream和FileOutputStream中類意外的行爲,在進出JAVA

/** 
    * A handle to the standard input stream. Usually, this file 
    * descriptor is not used directly, but rather via the input stream 
    * known as <code>System.in</code>. 
    * 
    * @see java.lang.System#in 
    */ 
    public static final FileDescriptor in = new FileDescriptor(0); 

    /** 
    * A handle to the standard output stream. Usually, this file 
    * descriptor is not used directly, but rather via the output stream 
    * known as <code>System.out</code>. 
    * @see java.lang.System#out 
    */ 
    public static final FileDescriptor out = new FileDescriptor(1); 

在這裏,我直接用它,而不是System.out。現在,檢查以下項目:

import java.io.*; 
public class First 
{ 
    public static void main(String[] args) throws Exception 
    { 
     FileInputStream fis = new FileInputStream(FileDescriptor.out); 
     byte[] b = new byte[8]; 
     System.out.println(fis.read(b));//6 
     for(byte b1: b) 
     { 
      System.out.println(b1); 
     } 
    } 
} 

輸入

hello 

輸出

6 
    104 
    101 
    108 
    108 
    111 
    10 
    0 
    0 

注意的是,即使我在構造函數中使用FileDescriptor.out,它是不會放棄任何錯誤併爲標準輸入流完美工作。

檢查多了一個方案:

import java.io.*; 
public class First 
{ 
    public static void main(String[] args) throws Exception 
    { 
     FileOutputStream fos = new FileOutputStream(FileDescriptor.in); 
     byte[] b = {65, 66, 67}; 
     fos.write(b); 
    } 
} 

輸出

ABC 

注意的是,即使我在構造函數中使用FileDescriptor.in,不給予任何錯誤,併爲工作完美標準輸出流。

我知道Java中的FileDescriptor是不透明的,我不應該將它與Linux中的文件描述符概念進行比較。我只是想知道它是如何在JAVA中創建的。如果一個靜態變量可以同時讀取和寫入,那麼需要三個(進出,錯誤)。

+0

我試了你的兩個代碼片段,並在這兩種情況下,我有一個java.io.IOException:訪問被拒絕。你的問題到底是什麼? – Armine

+0

另外,請查看:http://tutorials.jenkov.com/java-io/system-in-out-error.html瞭解更多有關System.in,System.out和System.err的信息。 – Armine

+0

它在Windows上顯示錯誤,但在Linux中運行。 –

回答

3

如果你從shell運行你的測試,而沒有重定向,那麼文件描述符0,1和2可能是相同的文件:/ dev/tty或類似的東西(你的終端)。

這就解釋了爲什麼你可以從這些描述符中讀取/寫入。