console的使用及引申的输入输出重定向问题

来源:互联网 发布:phantomjs pdf python 编辑:程序博客网 时间:2024/05/01 03:38

为了解决Scanner类输入可见的问题,java SE 6特别引入了Console类来实现这个目的,以下是Console的使用示例:

import java.io.Console;

import java.util.*;

public class  Welcome

{

public static void main(String[] args)

{

Console cons=System.console();

String username=cons.readLine("your name:");

char[] passwd=cons.readPassword("your password:");

System.out.println("hai! "+username+" this year,your password is "+passwd);

}

}

  但是采用console对象处理输入不如采用scanner方便,每次只能读取一行输入,而没有能够读取一个单词或一个数组的方法。而且,需要注意的一点是:Java.io.Console只能用在标准输入、输出流未被重定向的原始控制台中使用,在 Eclipse或者其他 IDE的控制台是用不了的。

  对这句话的解释(Java.io.Console 只能用在标准输入、输出流未被重定向的原始控制台中使用,在 Eclipse 或者其他 IDE 的控制台是用不了的):一般情况下,System.in代表的是键盘、System.out是代表的控制台(显示器)。当程序通过System.in来获取输入的时候,默认情况下,是从键盘读取输入;当程序试图通过System.out执行输出时,程序总是输出到显示器。如果我们想对这样的情况做一个改变,例如获取输入时,不是来自键盘,而是来自文件或其他的位置;输出的时候,不是输出到显示器上显示,而是输出到文件或其他位置,这就是所谓的输入输出重定向。很明显,在Eclipse 或者其他IDE 的控制台已经进行了重定向。

  重定向的方法:

1.重定向的标准输出,Static void setOutPrintStream out

  /**

* 重定向标准输出流

* 1.初始化PrintStream对象

* 2.调用System.setOut()方法,将标准输出流重定向到PrintStraem对象

* 3.操作System.out

*/

public class ReOut {

public static void main(String[] args) throws FileNotFoundException {

//初始化一个PrintStream对象

PrintStream ps = new PrintStream(new FileOutputStream("c:/myDoc/hello.txt"));

//重定向标准输出流,重定向到上面指定的文件

System.setOut(ps);

//使用PrintStream对象向流中写信息

System.out.print("测试一下,看重定向是否成功");

//关闭流

ps.close();

}

}

2.重定向的标准输入

Static void setInInputStream in

/**

* 重定向标准输入流

* 1.有一个已经初始化的输入流InputStream

* 2.调用System.setIn()方法,将标准输入流重定向到目的输入流

* 3.System.in进行读取操作

* @author ghp

*

*/

 

public class ReIn {

public static void main(String[] args) throws IOException {

//实例化FileinputStream对象

FileInputStream fis = new FileInputStream("c:/myDoc/hello.txt");

//重定向标准输入流

System.setIn(fis);

//读取System.in标准输入流中的内容

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//输出System.in中的内容

String line = null;

System.out.println("==============开始读取标准输入流=============");

while((line = br.readLine()) !=null){

System.out.println(line);

}

//关闭流

br.close();

fis.close();

System.out.println("=============读取输入流完毕============");

}

 

}

相关链接:http://blog.csdn.net/yj_fq/article/details/41856073

0 0