java.io.Console的使用以及重定向标准输出/输入
来源:互联网 发布:js修改sass变量 编辑:程序博客网 时间:2024/06/07 03:03
在看console的时候 看到了个这个类只适用于标准的输入 输出流未被重定向的原始控制台中 比如 CMD中的那个对话框 在ECLIPSE中无法使用
import java.io.Console; public class TestConsole { public static void main(String[] args) { Console console=System.console(); if(console!=null) { System.out.println("input data"); String data=console.readLine(); System.out.println("data="+data); char[] pwds=console.readPassword(); System.out.println("pwds="+pwds); data=console.readLine("hello %s", "test"); System.out.println(data); pwds=console.readPassword("hello password %s", "test"); System.out.println(pwds); //输出 console.format("fuck %s\n", "you"); console.writer().println("finish"); console.flush(); }else{ System.out.println("console==null"); } } }
以上是这个类的具体命令 其实和System.out System.in 差不多
然后说这个重新定向
Java的标准输入/输出分别通过System.in和System.out来代表,在默认的情况下分别代表键盘和显示器,当程序通过System.in来获得输入时,实际上是通过键盘获得输入。当程序通过System.out执行输出时,程序总是输出到屏幕。
在System类中提供了三个重定向标准输入/输出的方法
static void setErr(PrintStream err) 重定向“标准”错误输出流
static void setIn(InputStream in) 重定向“标准”输入流
static void setOut(PrintStream out)重定向“标准”输出流
下面程序通过重定向标准输出流,将System.out的输出重定向到文件输出,而不是在屏幕上输出。
意思就是把输出 输入的东西换了个方向
然后是代码
import java.io.FileOutputStream; import java.io.PrintStream; public class Test { public static void main(String[] args) throws Exception { PrintStream ps=new PrintStream(new FileOutputStream("work")); System.setOut(ps); System.out.println("Hello World!"); } }
下面的代码将System.in重定向到文件输入,所以将不接受键盘输入
Java代码 收藏代码
import java.io.FileInputStream; import java.util.Scanner; public class Test { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("work"); System.setIn(fis); Scanner sc=new Scanner(System.in); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } } }
0 0
- java.io.Console的使用以及重定向标准输出/输入
- java.io.Console的使用以及重定向…
- 初学Java,IO之重定向标准输入\输出(四十五)
- Java重定向标准输入/输出
- Java重定向标准输入/输出
- Java重定向标准输入/输出
- Java标准输入/输出 重定向
- IO之转换流与重定向标准输入/输出
- 重定向标准输入/输出
- 重定向标准输入,输出以及错误流
- 重定向标准输入,输出以及错误流
- java的重定向标准IO
- Linux输入/输出重定向的使用
- IO:重定向标准输入流
- IO:重定向标准输出流
- linux 重定向 标准输入 标准输出 标准错误输出
- Linux标准输入/输出和重定向
- Linux标准输入/输出和重定向
- Android:CalledFromWrongThreadException
- eclipse自动补全的设置
- java程序员反射
- 计算机中那些事儿(八):再历装系统之终身学习
- 程序的装入和链接
- java.io.Console的使用以及重定向标准输出/输入
- 开关电容的基本知识
- Java学习日记之类和对象:静态成员与实例成员
- Leetcode Linked List Cycle
- shopnc用户登录session丢失问题
- javascript学习过程中的一些体会和重点(1)
- Eclipse配置Python环境
- 网络基本知识的总结
- In-Depth: Static Code Analysis