zoukankan      html  css  js  c++  java
  • java 输入输出IO流:标准输入/输出System.in;System.out;System.err;【重定向输入System.setIn(FileinputStream);输出System.setOut(printStream);】

    Java的标准输入输出分别通过System.in和System.out来代表的,在默认情况下它分别代表键盘和显示器,当程序通过System.in来获取输入时,实际上是从键盘读取输入 当程序试图通过 System.out 执行输出时,程序总是输出到屏幕:
     
    从System类的源码可以看出in;out;err这几个常量 的类型

    重定向标准输出到文件:System.setOut(printStream);

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    
    /**
     * @ClassName PrintStreamExample
     * @projectName: object1
     * @author: Zhangmingda
     * @description: XXX
     * date: 2021/4/18.
     */
    public class PrintStreamExample {
        public static void main(String[] args) {
            try(PrintStream printStream = new PrintStream(new FileOutputStream("输入输出文件读写/src/test/output/System.out.txt"))) {
                System.setOut(printStream);
                System.out.println("卧槽,打印到哪里了????"); //打印到文件里面了
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    重定向输入System.setIn(FileinputStream);

    import com.sun.jdi.PathSearchingVirtualMachine;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Scanner;
    
    /**
     * @ClassName InputStreamSystemInExample
     * @projectName: object1
     * @author: Zhangmingda
     * @description: XXX
     * date: 2021/4/18.
     */
    public class InputStreamSystemInExample {
        public static void main(String[] args) {
            try (InputStream inputStream = new FileInputStream("输入输出文件读写/src/test/output/System.out.txt")){
                System.setIn(inputStream);
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()){  //看看是否还有下一行
                    System.out.println(scanner.nextLine()); //打印下一行
                }
            }catch (FileNotFoundException e ){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

      

  • 相关阅读:
    Java System.getProperty vs System.getenv
    Bring JavaScript to your Java enterprise with Vert.x
    es4x 引用外部jar 包以及集成typescrip
    cube.js 最近的一些更新
    es4x 调用其他三方jar 包
    graalvm native image 试用
    es4x 使用nodejs 开发vertx 应用框架试用
    clojure 环境搭建
    restql 学习三 查询语言简单说明
    restql 学习二 几种查询模式
  • 原文地址:https://www.cnblogs.com/zhangmingda/p/14673954.html
Copyright © 2011-2022 走看看