• 【java】System成员输入输出功能out、in、err


     1 package System输入输出;
     2 
     3 import java.io.ByteArrayOutputStream;
     4 import java.io.File;
     5 import java.io.FileOutputStream;
     6 import java.io.IOException;
     7 import java.io.OutputStream;
     8 import java.util.function.Consumer;
     9 
    10 
    11 public class Test {
    12     public static void main(String[] args) throws IOException {
    13         /*
    14         try{
    15             int i=3/0;
    16         }catch(Exception e){
    17             e.printStackTrace();
    18             System.out.println(e);//输出信息红色
    19             System.err.println(e);//输出信息黑色
    20         }
    21         */
    22         //输出到屏幕
    23         OutputStream out=System.out;
    24         //输出到文件
    25         OutputStream out2=new FileOutputStream(new File("D:"+File.separator+"test.txt"));
    26         //输出到内存
    27         OutputStream out3=new ByteArrayOutputStream();
    28         //以上体现多态性
    29         out.write("Welcom to 中国
    ".getBytes());
    30         
    31         Consumer<String> consumer=System.out::println;
    32         consumer.accept("北京欢迎你!");
    33     }
    34 }
    System.out
     1 package System输入输出;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 
     6 public class Test {
     7     public static void main(String[] args) throws IOException {
     8         InputStream in=System.in;
     9         byte[] b=new byte[1024];
    10         System.out.println("请输入数据:");
    11         int len=in.read(b);
    12         System.out.println(new String(b,0,len));
    13     }
    14 }
    System.in

     设置好接收输入的上限:优点是输出时无乱码,缺点是长度限死了。

     1 package System输入输出;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 
     6 public class Test {
     7     public static void main(String[] args) throws IOException {
     8         InputStream in=System.in;
     9         StringBuffer sb=new StringBuffer();
    10         System.out.println("请输入数据:");
    11         int tmp=0;
    12         while((tmp=in.read())!=-1){
    13             if(tmp=='
    ')
    14                 break;
    15             sb.append((char)tmp);
    16         }
    17         System.out.println(sb);
    18     }
    19 }
    System.in接收无长度限制输入

     不限接收输入的上限:优点是可接收任意长度输入,缺点是输出有乱码。

  • 相关阅读:
    分页
    uuid算法
    mysql卸载安装
    安装和破解收费版idea
    css样式一开始不显示,点击显示隐藏
    各种技术网址
    vue加载高德地图,加标记点,点出文本框
    Security Traps 玩耍剧透(持续更新)
    最近做的一个小玩意踩的坑
    最近刷题的一个总结
  • 原文地址:https://www.cnblogs.com/xiongjiawei/p/6685483.html
Copyright © 2020-2023  润新知