java 21

标准输入输出流
  System类中的两个成员变量:
    public static final InputStream in “标准”输入流。
    public static final PrintStream out “标准”输出流。

    pnputStream is = System.in;
    printStream ps = System.out;

System.out; 标准输出流:

其实从上面就可以看出来了

        System.out.println("helloworld");

其实等于

        PrintStream ps = System.out;
        ps.println("helloworld");

注意:  

1 PrintStream ps = System.out;
2 //下面这两种方法,其实是一种方法是不存在的,注:()内没东西。
3 ps.print();
4 System.out.print();

来玩个有意思的东西:

如何让字节流变为字符流进行操作呢?

我们可以通过转换流来玩,字节流→转换流→字符流

 1     public static void main(String[] args) throws IOException {
 2                 // 获取标准输入流
 3                 // // PrintStream ps = System.out;
 4                 // // OutputStream os = ps;
 5                 // OutputStream os = System.out; // 多态
 6                 // // 我们用字符流来包装字符流,表面是字符流,其实底层用的还是字节流(标准输出流)
 7                 // OutputStreamWriter osw = new OutputStreamWriter(os);
 8                 // BufferedWriter bw = new BufferedWriter(osw);
 9                 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
10                         System.out));
11 
12                 bw.write("hello");
13                 bw.newLine();
14                 bw.write("world");
15                 bw.newLine();
16                 bw.flush();
17                 
18                 bw.close();
19     }

。。。麻烦要死,理解就好了吧

System.in; 标准输入流:


输入流和输出流差不多,不用介绍。下面说下一个有意思的东西:

到JDK1.7为止,有3种方式实现键盘录入:

    1、main方法的args接收参数:    

java HelloWorld hello world java

  2、Scanner (JDK1.5以后才有的)

1 Scanner sc = new Scanner(System.in);
2 String s = sc.nextLine();
3 int x = sc.nextInt();
4 ...

  那么,在JDK1.5之前,用的是这种方式:

3、通过字符缓冲流包装标准输入流实现:

 1     public static void main(String[] args) throws IOException {
 2         // //获取标准输入流
 3         // InputStream is = System.in;
 4         // 但是,这个一次只能获取一个字节。而我们想要的是一次获取一行数据
 5         // 要想实现,首先你得知道一次读取一行数据的方法是哪个呢?
 6         // readLine()
 7         // 而这个方法在BufferedReader类中,所以,我们应该创建BufferedReader的对象,但是底层还是的使用标准输入流
 8         // BufferedReader br = new BufferedReader(is);
 9         // 但是这里还是出现错误。原因是:字符缓冲流只能针对字符流操作,而InputStream是字节流,所以不能使用
10         // 要想使用的话,就只能把字节流转换为字符流,然后在通过字符缓冲流操作
11         
12         // InputStreamReader isr = new InputStreamReader(is);
13         // BufferedReader br= new BufferedReader(isr); 这两句可以写作下面一句
14         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15 
16         System.out.println("请输入一个字符串:");
17         String line = br.readLine();
18         System.out.println("你输入的字符串是:" + line);
19 
20         System.out.println("请输入一个整数:");
21         // int i = Integer.parseInt(br.readLine());
22         line = br.readLine();
23         int i = Integer.parseInt(line);
24         System.out.println("你输入的整数是:" + i);
25     }

结论:。。。还是用Scanner吧

  

何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5929281.html