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中创建的。如果一个静态变量可以同时读取和写入,那么需要三个(进出,错误)。
我试了你的两个代码片段,并在这两种情况下,我有一个java.io.IOException:访问被拒绝。你的问题到底是什么? – Armine
另外,请查看:http://tutorials.jenkov.com/java-io/system-in-out-error.html了解更多有关System.in,System.out和System.err的信息。 – Armine
它在Windows上显示错误,但在Linux中运行。 –