zoukankan      html  css  js  c++  java
  • 4、IO--字节转换流

    整个Java的I/O包中实际上分为字节流和字符流

    还存在一组”字节流--字符流“的转换类

    1、OutputStreamWriter:是Writer的子类,将输出的字符流变为字节流

      即将一个字符流的输出对象变为字节流的输出对象

    2、InputStreamReader:是Reader的子类,将输入的字节流转换为字符流

      即将一个字节流的输入对象变为字符流的输入对象

    关闭规则:

    由里到外

    字符流转换为字节流OutputStreamWriter

        public static void main(String[] args) throws IOException {
            
            //1、
            File file = new File("d:\test.txt");
            OutputStream out = new FileOutputStream(file);
            
            //2、
            Writer writer = null;
            writer = new OutputStreamWriter(out);
            
            //3、
            writer.write("天长地久");
            
            //4、
            writer.close();
            out.close();
            
        }

     字节流转换为字符流InputStreamReader

        public static void main(String[] args) throws IOException {
            
            //1、
            File file = new File("d:\test.txt");
            InputStream in = new FileInputStream(file);
            
            //2、
            InputStreamReader reader = null;
            reader = new InputStreamReader(in);
            
            //3、
            int res = 0;
            int len = 0;
            char [] b = new char[(int) file.length()];
            
            while((res = reader.read()) !=-1){
                b[len] = (char) res;
                len++;
            }
            
            //4、
            reader.close();
            in.close();
        
            System.out.println(new String(b));
        }
    }

     

  • 相关阅读:
    这几天都是在公司慢待
    电脑没有关机可能出现发博文dns异常(write)
    DOS/VBS
    SourceInsight
    CevaEclipse
    C/C++
    Matlab
    Matlab
    C语言
    Matlab
  • 原文地址:https://www.cnblogs.com/Mrchengs/p/10813245.html
Copyright © 2011-2022 走看看