---
title: "Java重定向标准输入/输出"
author: "perfect5085"
date: "2012-08-21T20:35:21Z"
tags: ["Java", "标准输入/输出", "重定向"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-08-21T20:35:21Z"
id: 1649774
url: "https://perfect5085.iteye.com/blog/1649774"
---

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重定向到文件输入，所以将不接受键盘输入

```
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());
		}
		

	}
	


	
}
```