说说 Java I/O 系统之标准 I/O
2017-06-30 17:14
197 查看
标准 I/O 在 Unix 中指的是程序所使用的单一信息流。程序的所有输入都来自于标准输入、所有输出都发送到标准输出,以及所有的错误都会发送到标准错误中。这样我们可以很容易把程序串起来,一个程序的标准输出是另一个程序的标准输入,是不是很强大呀O(∩_∩)O~
注意,readLine() 会抛出 IOException。还有一点,读取
这里使用了带两个参数的 PrintWriter 构造器。第二个参数为 true,表示开启了自动清空功能,这样才能在控制台看到实际的输出!
setIn(InputStream)
setOut(PrintStream)
setErr(PrintStream)
有时候会一次性输出大
4000
量的信息,而这些输出滚动的太快以至于无法阅读时,重定向输出就很有用:
这里,我们将标准输入接入文件,然后将标准输出和标准错误重定向到另一个文件。System.out 最开始先保存在参数中,最后再恢复。这样只有中间这一段的 System.out 被做了重定向处理。
还有一点,I/O 重定向操作的是字节流,所以我们这里使用了 FileInputStream 和 FileOutputStream。
1 从标准输入中读取数据
Java 的标准 I/O 模型提供了System.in、System.out 和 System.err。System.out 和 System.err 都已被包装成了 PrintStream 对象,但
System.in却没有,所以我们可以直接使用 System.out 和 System.err,而在读取
System.in之前必须先对其进行包装。
public class Echo { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String s; while ((s = stdin.readLine()) != null && s.length() != 0) System.out.println(s); // An empty line or Ctrl-Z teminates the program } }
注意,readLine() 会抛出 IOException。还有一点,读取
System.in时要加入缓冲能力。
2 把 System.out 转换为 PrintWriter
public class ChangeSystemOut { public static void main(String[] args) { PrintWriter out = new PrintWriter(System.out, true); out.println("Hello,world"); } }
这里使用了带两个参数的 PrintWriter 构造器。第二个参数为 true,表示开启了自动清空功能,这样才能在控制台看到实际的输出!
3 标准 I/O 的重定向
System 类提供了一些静态方法,我们可以利用这些方法对标准输入、标准输出以及错误 I/O 流进行重定向:setIn(InputStream)
setOut(PrintStream)
setErr(PrintStream)
有时候会一次性输出大
4000
量的信息,而这些输出滚动的太快以至于无法阅读时,重定向输出就很有用:
public class Redirecting { public static void main(String[] args) throws IOException { PrintStream console = System.out; BufferedInputStream in = new BufferedInputStream(new FileInputStream ("D:\\temp\\1\\1.txt")); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream ("D:\\temp\\1\\5.txt"))); System.setIn(in); System.setOut(out); System.setErr(out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; while ((s = br.readLine()) != null) System.out.println(s); out.close();// Remember this! System.setOut(console); } }
这里,我们将标准输入接入文件,然后将标准输出和标准错误重定向到另一个文件。System.out 最开始先保存在参数中,最后再恢复。这样只有中间这一段的 System.out 被做了重定向处理。
还有一点,I/O 重定向操作的是字节流,所以我们这里使用了 FileInputStream 和 FileOutputStream。
相关文章推荐
- 说说Java 7中的模块系统基本概念
- java--IO流-LineNumberReader,读取键盘录入,字符字节流转换,改变标准输入输出设备,异常的日志信息,系统信息
- 用JAVA轻松返回系统当前的标准日期-时间
- Hadoop实验:用java直接使用FileSystem以标准输出格式显示Hadoop文件系统中的文件
- 说说 Java I/O 系统之 RandomAccessFile 类
- 说说 Java I/O 系统之 Reader 与 Writer
- [Java IO]04_系统标准IO
- 标准缓存系统--JAVA读写锁的使用
- 说说 Java I/O 系统之输入与输出
- 说说 Java I/O 系统——读写文件的实用工具
- [Java IO]04_系统标准IO
- 说说 Java I/O 系统——如何执行操作系统的命令
- Java基础之IO流,打印系统信息至标准输出设备或文件中Properties.list()
- 一个超漂亮的Java版博客系统,内置14套皮肤,已经转化为标准的Eclipse项目,直接导入即可
- 说说 Java I/O 系统之 I/O 流的典型用法(带示例)
- 彻底明白Java的IO系统---JAVA之精髓IO流
- 通用JAVA邮件系统程序
- 彻底明白Java的IO系统(文摘)---JAVA之精髓IO流 ZHBK [原作]
- Windows系统托盘图标程序之Java实现
- 利用 Java 平台的特性建造一个令人瞩目的系统