只要使用OutputStream
对象就可使用System.out
和System.err
对象引用。只要可以使用InputStream
对象就可以使用System.in
对象。
System
类提供了三个静态设置器方法setOut()
,setIn()
和stdErr()
,以用自己的设备替换这三个标准设备。
要将所有标准输出重定向到一个文件,需要通过传递一个代表文件的PrintStream
对象来调用setOut()
方法。
import java.io.PrintStream
import java.io.FileOutputStream
import java.io.File
public class Main {
public static void main(String[] args) throws Exception {
File outFile = new File("stdout.txt")
PrintStream ps = new PrintStream(new FileOutputStream(outFile))
System.out.println(outFile.getAbsolutePath())
System.setOut(ps)
System.out.println("Hello world!")
System.out.println("Java I/O is cool!")
}
}
上面的代码生成以下结果。
F:\website\yiibai\worksp\stdout.txt
标准输入流
可以使用System.in
对象从标准输入设备(通常是键盘)读取数据。
当用户输入数据并按Enter
键时,输入的数据用read()
方法每次返回一个字节的数据。
以下代码说明如何读取使用键盘输入的数据。\n
是Windows上的换行字符。
import java.io.IOException
public class Main {
public static void main(String[] args) throws IOException {
System.out.print("Please type a message and press enter: ")
int c = &apos\n&apos
while ((c = System.in.read()) != &apos\n&apos) {
System.out.print((char) c)
}
}
}
由于System.in
是InputStream
的一个实例,可以使用任何具体的装饰器从键盘读取数据 例如,可以创建一个BufferedReader
对象,并从键盘读取数据一行一次作为字符串。
上面的代码生成以下结果。
Please type a message and press enter: System.in.read demo...
System.in.read demo...
示例
以下代码说明如何将System.in
对象与BufferedReader
一起使用。程序不断提示用户输入一些文本,直到用户输入Q
或q
来退出程序。
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.IOException
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
String text = "q"
while (true) {
System.out.print("Please type a message (Q/q to quit) and press enter:")
text = br.readLine()
if (text.equalsIgnoreCase("q")) {
System.out.println("We have decided to exit the program")
break
} else {
System.out.println("We typed: " + text)
}
}
}
}
如果想要标准输入来自一个文件,必须创建一个输入流对象来表示该文件,并使用System.setIn()
方法设置该对象,如下所示。
FileInputStream fis = new FileInputStream("stdin.txt")
System.setIn(fis)
// Now System.in.read() will read from stdin.txt file
上面的代码生成以下结果。
Please type a message (Q/q to quit) and press enter:abc
We typed: abc
Please type a message (Q/q to quit) and press enter:yes or no?
We typed: yes or no?
Please type a message (Q/q to quit) and press enter:yes
We typed: yes
Please type a message (Q/q to quit) and press enter:q
We have decided to exit the program
标准错误设备
标准错误设备用于显示任何错误消息。Java提供了一个名为System.err
的PrintStream
对象。使用它如下:
System.err.println("This is an error message.")