美文网首页
数据持久化----文件存储

数据持久化----文件存储

作者: 爱做梦的严重精神病患者 | 来源:发表于2018-09-09 16:29 被阅读0次

    1.数据持久化----文件存储

    Java IO流:
     根据处理数据类型的不同分为:字符流和字节流
     根据数据流向不同分为:输入流和输出流

    输入字节流相关类:以InputStream为结尾。
    输出字节流相关类:以OutputStream为结尾。
    输入字符流相关类:以Reader为结尾。
    输出字符流相关类:以Writer为结尾。

    缓冲流(BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter):在节点流(直接与数据相连,例:没有Buffered前缀的相关类)的基础上增加了缓冲功能,避免频繁读写硬盘。

    输入字节流读取的时候:需要利用数组。

     byte[] b=new byte[1024];   //代表一次最多读取1KB的内容
     int length = 0 ; //代表实际读取的字节数
                while( (length = bufferedInputStream.read( b ) )!= -1 ){
                    //length 代表实际读取的字节数
                    bufferedOutputStream.write(b, 0, length );
                }
    

    输入字符流读取的时候:每次只读取一行,并且需要换行。

    String result = null ; //每次读取一行的内容
                while (  (result = bufferedReader.readLine() ) != null ){
                    bufferedWriter.write( result );  //把内容写入文件
                    bufferedWriter.newLine();  //换行,result 是一行数据,所以没写一行就要换行 
                }
    

    字节数组输入流(ByteArrayInputStream):将字节数组转化为输入流。

            String mes = "hello,world" ;
            byte[] b = mes.getBytes() ;
            
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( b ) ;
            int result = -1  ;
    
            while( ( result = byteArrayInputStream.read() ) != -1){
                System.out.println( (char) result );
            }
    

    字节数组输出流(ByteArrayOutputStream):将字节数组写入到输出流中。

            byte[] b = mes.getBytes() ;
    
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
            try {
                //将b写入字节数组输出流
                byteArrayOutputStream.write( b );
    
                FileOutputStream fileOutputStream = new FileOutputStream( new File( "F:/123.txt" ) ) ;
    
                //  将字节输出流中的数据写入文件输出流中
                byteArrayOutputStream.writeTo( fileOutputStream ) ;
    
                fileOutputStream.flush();
            }
    

     只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。

    Java_IO流.jpg

    相关文章

      网友评论

          本文标题:数据持久化----文件存储

          本文链接:https://www.haomeiwen.com/subject/xefdgftx.html