Java的标准输入输出分别通过System.in和System.out来代表,默认情况他们分别代表键盘和显示器,在System.in类里提供了三个重定向标准输入输出的方法:
static void setErr(PrintStram err)
功能:重定向标准错误输出
参数:
返回值:无
static void setIn(InputStream in)
功能:重定向标准输入
参数:
返回值:无
static void setOut(PrintStram out)
功能:重定向标准输出
参数:
返回值:无
下面两个例子,分别是标准输出重定向:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
   |  import java.io.*;
  public class RedirectOut { 	public static void main(String[] args) 	{ 		try ( 			 			var ps = new PrintStream(new FileOutputStream("out.txt"))) 		{ 			 			System.setOut(ps); 			 			System.out.println("普通字符串"); 			 			System.out.println(new RedirectOut()); 		} 		catch (IOException ex) 		{ 			ex.printStackTrace(); 		} 	} }
 
 
 
  | 
标准输入重定向:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   |  import java.util.*; import java.io.*;
  public class RedirectIn { 	public static void main(String[] args) 	{ 		try ( 			var fis = new FileInputStream("RedirectIn.java")) 		{ 			 			System.setIn(fis); 			 			var sc = new Scanner(System.in); 			 			sc.useDelimiter("\n"); 			 			while (sc.hasNext()) 			{ 				 				System.out.println("键盘输入的内容是:" + sc.next()); 			} 		} 		catch (IOException ex) 		{ 			ex.printStackTrace(); 		} 	} }
 
 
 
  |