java输出重定向

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

System类里提供了3个重定向标准输入,输出的方法.

static void setErr(PrintStream err):重定向”标准”错误输出流. 
static void setIn(InputStream in):重定向”标准”输入流 
static void setOut(PrintStream out):重定向”标准”输出流.

 

下面的程序通过重定向标准输出流,将System.out的输出重定向到文件输出,而不是屏幕上输出.运行程序后D盘下有文件生成.

注意:路径不可以写成c:\user\local\myDir\test1.txt这种,必须用两个左斜线作为分割。 如果路径直接写出test1.txt,那会默认在项目根目录下创建。 

public class RedirectOut {

    public static void main(String[] args) throws FileNotFoundException {
        //一次性创建PrintStream输出流
        PrintStream ps=new PrintStream(new FileOutputStream("D://test1.txt"));
        //将标准输出重定向到PS输出流
        System.setOut(ps);
        //向标准输出输出一个字符串
        System.out.println("Hello world");
    }
}

  

下面是重定向标准输入,从而可以把System.in重定向到指定文件,而不是键盘输入.首先创建了一个FileInputStream输入流,并使用System的setIn方法将系统标准输入重定向到该文件输入流.运行程序,直接输出的是文本文件的内容,表明程序不再使用键盘作为输入,而是使用文本文件作为标准输入源.

package org.credo.io;

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

public class RedirectIn {

    public static void main(String[] args) throws FileNotFoundException {
        FileInputStream fis=new FileInputStream("D://test.txt");
        //将标准输入重定向到fis输入流
        System.setIn(fis);
        //使用System.in创建Scanner对象,用于获取标准输入
        Scanner sc=new Scanner(System.in);
        //增加下面一行只把回车作为分隔符
        sc.useDelimiter("\n");
        //判断是否还有下一个输入项
        while(sc.hasNext()){
            //输出输入项
            System.out.println("键盘输入的内容是:"+sc.next());
        }
    }

}

  

猜你喜欢

转载自www.cnblogs.com/xinruyi/p/10202345.html