zoukankan      html  css  js  c++  java
  • 字符流,字节流,属性集(Properties)

    字节输入流(InputStream)

      java.io.InputStream抽象类是表示字节输入流的所有类的超类.可以读取字节信息到内存中.它定义了字节输入流的基本共性功能方法.

    public void close:关闭此输入流并释放与此流相关联的任何系统资源.

    public abstract int read():从输入流读取数据的下一个字节.

    public int read(byte[] b):从输入流中读取一些字节数,并将他们存储到字节数组b中.

    注意:

      close方法,当完成流的操作时,必须调用此方法,释放系统资源.

    FileInputStream类

      java.io.FileInputStream类是文件输入流,从文件中读取字节.

    构造方法:

      FileInputStream(File file):通过打开与实际文件的连接来创建一个FileInputStream,该文件由文件系统中的File对象file命名.

      FilInputStream(String name):通过打开与实际文件的连接来创建一个FileInputStream,该文件由文件系统中的路径名name命名.

    当你创建一个流对象时,必须传入一个文件路径.该路径下,如果没有该文件,会抛出FileNotFoundException.

    构造举例,代码如下:

    public class FileInputStreamConstructor throws IOException{
        public static void main(String[] args) {
         // 使用File对象创建流对象    
            File file = new File("a.txt");
            FileInputStream fos new FileInputStream(file);
         
            // 使用文件名称创建流对象
            FileInputStream fos = new FileInputStream("b.txt");
        }
    }

    读取字节数据

    读取字节:read方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回-1,代码演示:

    public class FISRead {
        public static void main(String[] args) throws IOException{
           // 使用文件名称创建流对象  
           FileInputStream fis = new FileInputStream("read.txt"); 
           // 读取数据,返回一个字节  
            int read = fis.read();
            System.out.println((char) read);
            read = fis.read();
            System.out.println((char) read);
            read = fis.read();
            System.out.println((char) read);
            read = fis.read();
            System.out.println((char) read);
            read = fis.read();
            System.out.println((char) read);
           // 读取到末尾,返回‐1  
           read = fis.read(); 
            System.out.println( read);
    // 关闭资源        
            fis.close();
        }
    }
    输出结果:
    a
    b
    c
    d
    e
    ‐1

    使用循环改进读取方式

    public class FISRead {
        public static void main(String[] args) throws IOException{
           // 使用文件名称创建流对象  
           FileInputStream fis = new FileInputStream("read.txt"); 
           // 定义变量,保存数据  
            int b ;
            // 循环读取
            while ((b = fis.read())!=‐1) {
                System.out.println((char)b);
            }
    // 关闭资源        
            fis.close();
        }
    }
    输出结果:
    a
    b
    c
    d
    e

    注意:虽然读取了一个字节,但是会自动提升为int类型,所以需要强转.

    流操作完毕后,必须释放系统资源,调用close方法,

    使用字节数组读取:read(byte[] b),每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时返回-1.

    public class FISRead {
        public static void main(String[] args) throws IOException{
           // 使用文件名称创建流对象.  
           FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde 
           // 定义变量,作为有效个数  
            int len ;
            // 定义字节数组,作为装字节数据的容器  
            byte[] b = new byte[2];
            // 循环读取
            while (( len= fis.read(b))!=‐1) {
               // 每次读取后,把数组变成字符串打印 
                System.out.println(new String(b));
            }
    // 关闭资源        
            fis.close();
        }
    }
    输出结果:
    ab
    cd
    ed

    最后一组数据是错误数据d,由于最后一次读取时,只读取了一个字节e,数组中,上次读取的数据没有被完全替换,所以要通过len,获取有效的字节.

    public class FISRead {
        public static void main(String[] args) throws IOException{
           // 使用文件名称创建流对象.  
           FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde 
           // 定义变量,作为有效个数  
            int len ;
            // 定义字节数组,作为装字节数据的容器  
            byte[] b = new byte[2];
            // 循环读取
            while (( len= fis.read(b))!=‐1) {
               // 每次读取后,把数组的有效字节部分,变成字符串打印 
                System.out.println(new String(b,0,len));//  len 每次读取的有效字节个数
            }
    // 关闭资源        
            fis.close();
        }
    }
    输出结果:
    ab
    cd
    e

    注意:使用数组读取,每次读取多个字节,减少了系统间的IO操作次数,从而提高了读写的效率,建议开发中使用.

    字节流练习:图片复制

    复制图片的原理:

    从已有文件中读取字节,将该字节写出到另一个文件中.

    public class Copy {
        public static void main(String[] args) throws IOException {
            // 1.创建流对象
            // 1.1 指定数据源
            FileInputStream fis = new FileInputStream("D:\test.jpg");
            // 1.2 指定目的地
            FileOutputStream fos = new FileOutputStream("test_copy.jpg");
            // 2.读写数据
            // 2.1 定义数组
            byte[] b = new byte[1024];
            // 2.2 定义长度
            int len;
            // 2.3 循环读取
            while ((len = fis.read(b))!=‐1) {
                // 2.4 写出数据
                fos.write(b, 0 , len);
            }
            // 3.关闭资源
            fos.close();
            fis.close();
        }
    }

    这个是通过写入流读取到内存,然后再使用输出流写出到指定的文件中.

    注意:关闭流的时候,要注意,流的关闭原则:先开后关

    字符流

    当使用字节流读取文本文件时,可能会有一个小问题,就是遇到中文字符时,可能不会显示完整的字符,那是因为中文字符可能占用多个字节存储,所以java提供了一些字符流类,以字符为单位读写数据,专门用于处理文本文件.

    字符输入流

    java.io.Reader抽象类是表示用于读取字符流的所有的超类,可以读取字符信息到内存中,它定义了字符输入流的基本共性功能方法.

    public void close():关闭此流并释放与此流相关联的任何系统资源.

    public int read():从输入流读取一个字符.

    public int read(char[] cbuf):从输入流中读取一些字符,并将他们存储到字符数组中cbuf中.

    FileReader类

    java.io.FileReader类是读取字符文件的便利类,构造时使用系统默认的字符编码和默认字节缓冲区.

    注意:字符编码:字节与字符的对应规则.Windows系统的中文编码默认是GBK编码表.

    idea中UTF-8

    2.字符缓冲区:一个字节数组,从来临时存储字节数据.

    构造方法:

      FileReader(File file):创建一个新的FileReader,给定要读取的File对象.  

      FileReader(String fileName):创建一个新的FileReader,给定要读取的文件的名称.

    当你创建一个流对象时,必须传入一个文件路径.类似于FileInputStream.

    构造举例,代码如下:

    public class FileReaderConstructor throws IOException{
        public static void main(String[] args) {
         // 使用File对象创建流对象    
            File file = new File("a.txt");
            FileReader fr new FileReader(file);
         
            // 使用文件名称创建流对象
            FileReader fr = new FileReader("b.txt");
        }
    }

    读取字符数据

    读取字符:read方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1,循环读取,

    public class FRRead {
        public static void main(String[] args) throws IOException {
           // 使用文件名称创建流对象
           FileReader fr = new FileReader("read.txt"); 
           // 定义变量,保存数据  
            int b ;
            // 循环读取
            while ((b = fr.read())!=‐1) {
                System.out.println((char)b);
            }
    // 关闭资源        
            fr.close();
        }
    }
    输出结果:
    程
    序
    员

    虽然读取了一个字符,但是会自动提升为int类型.

    使用字符数组读取:read(char[] cbuf),每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1.

    public class FRRead {
        public static void main(String[] args) throws IOException {
           // 使用文件名称创建流对象  
           FileReader fr = new FileReader("read.txt"); 
           // 定义变量,保存有效字符个数  
            int len ;
            // 定义字符数组,作为装字符数据的容器
             char[] cbuf = new char[2];
            // 循环读取
            while ((len = fr.read(cbuf))!=‐1) {
                System.out.println(new String(cbuf));
            }
    // 关闭资源        
            fr.close();
        }
    }
    输出结果:
    程序
    员序

    获取有效的字符改进

    public class FISRead {
        public static void main(String[] args) throws IOException {
           // 使用文件名称创建流对象  
           FileReader fr = new FileReader("read.txt"); 
           // 定义变量,保存有效字符个数  
            int len ;
      // 定义字符数组,作为装字符数据的容器
            char[] cbuf = new char[2];
            // 循环读取
            while ((len = fr.read(cbuf))!=‐1) {
                System.out.println(new String(cbuf,0,len));
            }
         // 关闭资源    
            fr.close();
        }
    }
    输出结果:
    程序
    员

    字符输出流(Writer)

    java.io.writer抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写到目的地,它定义了字节输出流的基本共性功能方法.

    public abstract void close():关闭此输出流并释放与此流相关联的任何系统资源.

    public abstract void flush():刷新此输出流并强制任何缓冲的输出字符被写出.

    public void write(int c):写出一个字符.

    public void write(char[] cbuf):将b.length字符从指定的字符数组写出此输出流.

    public abstract void write(char[] b,int off,int len):从指定的字符数组写出len字符,从偏移量off开始输出到此输出流.

    public void write(String str):写出一个字符串.

    FileWriter类

    java.io.FileWriter类是写出字符到文件的便利类.构造时使用系统默认的字符编码和默认字节缓冲区.

    构造方法:

    FileWriter(File file):创建一个新的FileWriter,给定要读取的File对象.

    FileWriter(String fileName):创建一个新的FileWriter,给定要读取的文件的名称.

    当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream.

    构造举例:

    public class FileWriterConstructor {
        public static void main(String[] args) throws IOException {
         // 使用File对象创建流对象    
            File file = new File("a.txt");
            FileWriter fw new FileWriter(file);
         
            // 使用文件名称创建流对象
            FileWriter fw = new FileWriter("b.txt");
        }
    }

    基本写出数据

    写出字符:write(int b)方法,每次可以写出一个字符数据,

    public class FWWrite {
        public static void main(String[] args) throws IOException {
            // 使用文件名称创建流对象
            FileWriter fw = new FileWriter("fw.txt");    
           // 写出数据  
           fw.write(97); // 写出第1个字符  
           fw.write('b'); // 写出第2个字符  
           fw.write('C'); // 写出第3个字符  
           fw.write(30000); // 写出第4个字符,中文编码表中30000对应一个汉字。  
         
           /*  
            【注意】关闭资源时,与FileOutputStream不同。
            如果不关闭,数据只是保存到缓冲区,并未保存到文件。  
            */
            // fw.close();
        }
    }
    输出结果:
    abC田

    注意:1.虽然参数为int类型四个字节,但是只会保留一个字符的信息写出.

      2.未调用close方法,数据只是保存到了缓冲区,并未写出到文件中.

    关闭和刷新

    因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中,但是关闭的流对象,是无法继续洗出数据的,如果我们既想写出数据,又想继续使用流,就需要flush方法了.

    flush:刷新缓冲区,刘独享可以继续使用.

    close:关闭流,释放系统资源.关闭前会刷新缓冲区.

    public class FWWrite {
        public static void main(String[] args) throws IOException {
    // 使用文件名称创建流对象
            FileWriter fw = new FileWriter("fw.txt");
            // 写出数据,通过flush
            fw.write('刷'); // 写出第1个字符
            fw.flush();
            fw.write('新'); // 继续写出第2个字符,写出成功
            fw.flush();
         
           // 写出数据,通过close  
            fw.write('关'); // 写出第1个字符
            fw.close();
            fw.write('闭'); // 继续写出第2个字符,【报错】java.io.IOException: Stream closed
            fw.close();
        }
    }

    注意:即便是flush方法写出了数据,操作的最后还是要调用close方法,释放系统资源.

    写出其他数据:

    写出字符数组:write(char[] cbuf)和write(char[] cbuf,int off,int len),每次可以写出字符数组中的数据,用法类似FileOutPutStream:

    public class FWWrite {
        public static void main(String[] args) throws IOException {
            // 使用文件名称创建流对象
            FileWriter fw = new FileWriter("fw.txt");    
           // 字符串转换为字节数组  
           char[] chars = "程序员".toCharArray();  
         
           // 写出字符数组  
           fw.write(chars); // 程序员  
           
    // 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。        
            fw.write(b,2,2); // 程序
         
           // 关闭资源  
            fos.close();
        }
    }

    写出字符串:write(String str)和write(String str,int off ,int len),每次可以写出字符串中的数据,更为方便,

    public class FWWrite {
        public static void main(String[] args) throws IOException {
            // 使用文件名称创建流对象
            FileWriter fw = new FileWriter("fw.txt");    
           // 字符串  
           String msg = "程序员";  
         
           // 写出字符数组
    fw.write(msg); //
         
    // 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。        
            fw.write(msg,2,2); // 程序  
           
            // 关闭资源
            fos.close();
        }
    }

    续写和换行:操作类似于FileOutputStream.

    public class FWWrite {
        public static void main(String[] args) throws IOException {
            // 使用文件名称创建流对象,可以续写数据
            FileWriter fw = new FileWriter("fw.txt",true);    
           // 写出字符串  
            fw.write("资深");
           // 写出换行  
           fw.write("
    ");  
           // 写出字符串  
       fw.write("程序员");      
           // 关闭资源  
            fw.close();
        }
    }
    输出结果:
    资深
    程序员

    注意:字符流,只能操作文本文件,不能操作图片,视频等非文本文件.

    当我们单纯读或者写文本文件时,使用字符流,其他情况使用字节流.

    IO异常处理

    JDK7前处理:

    之前的入门练习,我们一直把异常抛出,而实际开发中并不能这样处理,建议使用try...catch...finally代码块,处理异常部分.

    public class HandleException1 {
        public static void main(String[] args) {
           // 声明变量  
            FileWriter fw = null;
            try {
                //创建流对象
                fw = new FileWriter("fw.txt");
                // 写出数据
                fw.write("程序员"); //程序员
            } catch (IOException e) {
             e.printStackTrace();
            } finally {
                try {
                    if (fw != null) {
                        fw.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    JDK7的处理

    还可以使用JDK7优化后的try-with-resource语句,该语句确保了每个资源在语句结束时关闭,所谓的资源(resource)是指在程序完成后,必须关闭的对象.

    格式:

    try (创建流对象语句,如果多个,使用';'隔开) {
    // 读写数据    catch (IOException e) {
    e.printStackTrace();    
    }
    public class HandleException2 {
        public static void main(String[] args) {
           // 创建流对象  
            try ( FileWriter fw = new FileWriter("fw.txt"); ) {
                // 写出数据
                fw.write("程序员"); //程序员
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    属性集

    概述:java.util.Properties继承于Hashtable,来表示一个持久的属性集,它使用键值结构存储数据,每个键及其对应值都是一个字符串,该类也被许多java类使用,比如获取系统属性时,System.getProperties方法就是放回一个Properties对象.

    Properties类

    构造方法:

    public Properties():创建一个空的属性列表.

    基本的存储方法:

    public Object setProperty(String key,String value):保存一对属性.

    public String getProperty(String key):使用此属性列表中指定的键搜索属性值.

    pubic Set<String> stringPropertyNames():所有键的名称的集合.

    public class ProDemo {
        public static void main(String[] args) throws FileNotFoundException {
            // 创建属性集对象
            Properties properties = new Properties();
            // 添加键值对元素
            properties.setProperty("filename", "a.txt");
            properties.setProperty("length", "209385038");
            properties.setProperty("location", "D:\a.txt");
            // 打印属性集对象
            System.out.println(properties);
            // 通过键,获取属性值
            System.out.println(properties.getProperty("filename"));
            System.out.println(properties.getProperty("length"));
            System.out.println(properties.getProperty("location"));
            // 遍历属性集,获取所有键的集合
            Set<String> strings = properties.stringPropertyNames();
            // 打印键值对
            for (String key : strings ) {
               System.out.println(key+" ‐‐ "+properties.getProperty(key));  
            }
        }
    }
    输出结果:
    {filename=a.txt, length=209385038, location=D:a.txt}
    a.txt
    209385038
    D:a.txt
    filename ‐‐ a.txt
    length ‐‐ 209385038
    location ‐‐ D:a.txt

    与流相关的方法

    public void load(InputStream inStream):从字节输入流中读取键值对.

    参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了.文本数据格式:

    filename=a.txt
    length=209385038
    location=D:a.txt
    public class ProDemo2 {
        public static void main(String[] args) throws FileNotFoundException {
            // 创建属性集对象
            Properties pro = new Properties();
            // 加载文本中信息到属性集
            pro.load(new FileInputStream("read.txt"));
            // 遍历集合并打印
            Set<String> strings = pro.stringPropertyNames();
            for (String key : strings ) {
               System.out.println(key+" ‐‐ "+pro.getProperty(key));  
            }
         }
    }
    输出结果:
    filename ‐‐ a.txt
    length ‐‐ 209385038
    location ‐‐ D:a.txt

    文本中的数据,必须是键值对形式,可以使用空格,等号,冒号等符号分隔.

  • 相关阅读:
    CentOS7下搭建hadoop2.7.3完全分布式
    在linux命令行利用SecureCRT上传下载文件
    SPDY和HTTP
    哈希表的工作原理
    LVS(Linux Virtual Server)
    Discuz x3 UCenter实现同步登陆原理
    Goroutine(协程)为何能处理大并发?
    缓存与DB数据一致性问题解决的几个思路
    固态硬盘SSD与闪存(Flash Memory)
    堆和栈的区别(转过无数次的文章)
  • 原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/10793314.html
Copyright © 2011-2022 走看看