zoukankan      html  css  js  c++  java
  • System对IO的支持

    System类中三个常量:

    out:表示的是一个标准的输出,输出的位置是显示器

    err:表示错误,错误的输出

    in:表示的是键盘的输入,标准输入

    一,System.out使用

    import java.io.*;

    public class SystemDemo {
     public static void main(String args[])
     {
       OutputStream out=System.out;//此时out具备了向屏幕输出的能力
       try {
      out.write("hello world".getBytes());
      out.close();
       } catch (IOException e) {
      e.printStackTrace();
     }
     }
    }

    二,System.err

    import java.io.*;

    public class SystemDemo {
     public static void main(String args[])
     {
      try {
       Integer.parseInt("hello");
      } catch (Exception e) {
       System.out.println(e);
       System.err.print(e);
      }
     }
    }

    System.err打印出错误

    三,System.in

    import java.io.*;

    public class SystemDemo {
     public static void main(String args[]) throws Exception
     {
      InputStream input=System.in;//准备键盘输入数据
      int len=0;
      StringBuffer buf=new StringBuffer();
       while(((len=input.read())!=-1))
       {
        char c=(char)len;
        if(c=='\n')
        {
         break;
        }
        buf.append(c);
       }
      System.out.println("输入的内容为:"+buf.toString());
     }
    }

    读取的是字节,如果想更好的读取操作,则只能使用BufferedReader类完成。

    四,输入,输出重定向

    System.out,System.err都有固定的输出目标,都是屏幕;System.in有固定的输入目标,都是键盘。但是在System类中提供了一系列的输入输出重定向的方法,可以改变System.out,System.err,System.in的输入输出位置。

    1,System.out重定向:public static void setOut(PrintStream out)

    2,System.err重定向:public static void setErr(PrintStream err)

    3,System.in重定向:public static void setIn(InputStream in)

    import java.io.*;


    public class RedeirectSystemOutDemo {

     public static void main(String args[]) throws IOException
     {
      File file=new File("d:"+File.separator+"demo.txt");
      try {
       //将输出改变到文件
       //System.setOut(new PrintStream(new FileOutputStream(file)));
          //System.out.println("fdsa");
          //
          System.setIn(new FileInputStream(file));
          InputStream input=System.in;
          int len=0;
          StringBuffer sbf=new StringBuffer();
          while((len=input.read())!=-1)
          {
          char c=(char)len;
          if(c!='\n')
          {
           sbf.append(c);
          }else
          {
           break;
          }
          }
          System.out.println(sbf.toString());
         
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      }  
     }
    }

  • 相关阅读:
    cookie、session和会话保持
    常见的一些专业术语的概念
    JS中的执行机制(setTimeout、setInterval、promise、宏任务、微任务)
    加密和解密
    ASCII 、UTF-8、Unicode编码
    localhost、127.0.0.1、本机ip、0.0.0.0 的区别
    使用Bootstrap框架的HTML5页面模板
    js判断是否在微信浏览器中打开
    js获取url的参数
    js动态生成下拉列表
  • 原文地址:https://www.cnblogs.com/jinzhengquan/p/1948386.html
Copyright © 2011-2022 走看看