其他分享
首页 > 其他分享> > IO P09 打印流

IO P09 打印流

作者:互联网

package file;

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

// 打印流
public class TestPrintStream {
    public static void main(String[] args) {
        try {
            PrintStream printStream = new PrintStream(new FileOutputStream("printStream.txt"));
            printStream.println("hello hike");
            printStream.println("hello bad world");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
重定向标准输出
package file;

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

// 打印流
public class TestPrintStream {
    public static void main(String[] args) {
        try {
            PrintStream printStream = new PrintStream(new FileOutputStream("printStream.txt"));
            // 重定向标准输出   System.out.println() 默认是输出到屏幕的,
            // 但是重定向之后, 就输出到指定的地方
            System.setOut(printStream);
            System.out.println("hello 无涯");
            System.out.println("hello 乌鸦");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

重定向标准输入

package file;

import java.io.*;
import java.util.Scanner;

public class TestPrintStream2 {
    public static void main(String[] args) {
        try (InputStream read = new FileInputStream("printStream.txt")) {
            // 打印流  重定向标准输入
            System.setIn(read);
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

标签:java,io,printStream,打印,System,IO,new,import,P09
来源: https://blog.csdn.net/xcq2yqq/article/details/117266437