Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
FileInputStream的意外行为&;FileOutputStream类,与JAVA中FileDescriptor的in和out静态成员一起使用时_Java_Stdin_File Descriptor_Fileinputstream_Fileoutputstream - Fatal编程技术网

FileInputStream的意外行为&;FileOutputStream类,与JAVA中FileDescriptor的in和out静态成员一起使用时

FileInputStream的意外行为&;FileOutputStream类,与JAVA中FileDescriptor的in和out静态成员一起使用时,java,stdin,file-descriptor,fileinputstream,fileoutputstream,Java,Stdin,File Descriptor,Fileinputstream,Fileoutputstream,在FileDescriptor.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.Syst

在FileDescriptor.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);
       }
    }
}
输入

输出

  6
  104
  101
  108
  108
  111
  10
  0
  0
ABC
请注意,即使我在构造函数中使用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);
    }
}
输出

  6
  104
  101
  108
  108
  111
  10
  0
  0
ABC
请注意,即使我在构造函数中使用FileDescriptor.in,它也不会给出任何错误,也不会完美地用于标准输出流


我知道java中的文件描述符是不透明的,我不应该将其与Linux中的文件描述符概念进行比较。我只是想知道它是如何用JAVA创建的。如果一个静态变量既能读又能写,那么需要三个变量(输入、输出和错误)。

如果您在shell中运行测试,没有重定向,那么文件描述符0、1和2可能是同一个文件:/dev/tty或类似的文件(您的终端)


这就解释了为什么您可以从这些描述符中的任何一个进行读/写。

我尝试了您的两个代码片段,在这两种情况下,我都遇到了java.io.IOException:访问被拒绝。您的问题是什么?另外,请检查:有关System.in、System.out和System.err的更多详细信息。它在windows上显示错误,但在Linux中运行。