您的位置:首页 > 其它

输入和输出--重定向标准输入和输出

2014-12-30 17:11 148 查看
重定向标准输入和输出

Java的标准输入和输出分别通过system.in和system.out来代表,默认情况下他们分别代表键盘和显示器。

在system类中提供了3个重定向标准输入和输出的方法:

setErr(PrintStream err) 重新分配“标准”错误输出流。

setIn(InputStream in) 重新分配“标准”输入流。


setOut(PrintStream out) 重新分配“标准”输出流。

当然我们可以自己来写程序,修改我们应用程序的输入和输出。比如说现在不希望标准输出到显示器上,而是我自己的一个文件里面,或者是说我现在不需要从键盘上来录入内容,而是读我本地的一个文本。

具体的代码如下:



import java.io.FileOutputStream;
import java.io.PrintStream;

/**
*
* @version 1L
* @author LinkinPark
* @since 2014-12-30
* @motto 梦似烟花心似水,同学少年不言情
* @desc ^重定向标准输出流,讲system.out输出到指定的文件,而不是显示器上。
*/
public class Linkin
{

public static void main(String[] args)
{
PrintStream ps = null;
try
{
ps = new PrintStream(new FileOutputStream("src/LinkinPark..."));
System.setOut(ps);
System.out.println("这里重定向了标准输出。。。");
System.out.println(new Linkin());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ps != null)
{
ps.close();
}
}
}
}


import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

/**
*
* @version 1L
* @author LinkinPark
* @since 2014-12-30
* @motto 梦似烟花心似水,同学少年不言情
* @desc ^重定向标准输入流,将system.in重定向到指定的文件,而不是键盘输入了
*/
public class Linkin
{

public static void main(String[] args)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("src/LinkinPark...");
System.setIn(fis);
//使用system.in创建Scanner对象,用来获取标准输入
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");//增加分隔符
while (sc.hasNext())
{
System.out.println("指定的文件里面输入的内容是:" + sc.next());
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (fis != null)
{
try
{
//这里也要捕获异常的,有点恶心的
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: