栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IO流(各种流)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IO流(各种流)

文章目录
    • IO流
      • 字节流
      • 字节缓冲流
        • 字节流四种方式复制
      • 字符流
      • 字符缓冲流
      • 转换流
      • 集合与流
        • ArrayList
        • LinkedHashMap
      • 内存操作流
        • 歌曲串烧
      • 打印流
      • 标准输入输出流
        • 二种方式实现键盘录入
      • 随机访问流
      • 序列化流 反序列化流
        • 对象存取
      • Properties(双列集合)
        • 修改键值对
      • SequenceInputStream

IO流
概述
	IO流用来处理设备之间的数据传输
	Java对数据的操作是通过流的方式
	Java用于操作流的对象都在IO包中 java.io
分类
	1.按照数据流向
        输入流 读入数据
        输出流 写出数据
	2.按照数据类型
        字节流 可以读写任意类型的文件(音频 视频 文本文件)
        字符流 只能读写文本文件
	
          字节流	      字符流
    输入流 InPutStream   Reader
    输出流	OutPutStream  Writer
字节流
可以读写任何类型的文件 比如音频、视频、文本文件

FileInputStream
FileInputStream(File file) 
通过一个文件创建一个字节输入流
FileInputStream(String name) 
通过一个路径创建一个字节输入流
int read() 
从这个输入流读取一个字节的数据  
没有返回值就是-1 
int read(byte[] b) 
读到b.length从输入流到字节数组数据字节  
int read(byte[] b, int off, int len) 
读到len从输入流到字节数组数据字节  
void close() 
关闭流

FileOutputStream
FileOutputStream(File file) 
通过一个文件创建一个字节输出流  
FileOutputStream(File file, boolean append) 
通过一个文件创建一个字节输出流 
并判断是追加(true)还是覆盖(false)文件夹
void write(int b) 
将指定的字节写入该文件输出流中
void write(byte[] b) 
写b.length字节从指定的字节数组来此文件输出流  
void write(byte[] b, int off, int len) 
写len字节指定字节数组中的起始偏移off此文件输出流
void close() 
关闭此文件输出流并释放与此流关联的任何系统资源 

字节缓冲流
BufferedInputStream
BufferedInputStream(InputStream in) 
通过与其他字节输入流连用 创建BufferedInputStream  
BufferedInputStream(InputStream in, int size) 
通过与其他字节输入流连用
创建一个具有指定的缓冲区大小的BufferedInputStream
int read() 
与InputStream的read方法一样。  
int read(byte[] b, int off, int len) 
从这个字节的输入流读取到指定的字节数组中的字节从给定的偏移量开始 

BufferedOutputStream
BufferedOutputStream(OutputStream out) 
创建一个新的缓冲输出流 将数据写入到指定的基本输出流中  
BufferedOutputStream(OutputStream out, int size) 
创建一个新的缓冲输出流 用指定的缓冲区大小写数据到指定的基本输出流中  
void flush() 
刷新缓冲输出流。  
void write(byte[] b, int off, int len) 
写 len字节指定字节数组中的起始偏移 off这个缓冲输出流。  
void write(int b) 
将指定的字节写入该缓冲输出流中。  
字节流四种方式复制
public class Homework03 {
    public static void main(String[] args) throws IOException {
        //基本字节流一次读写一个字节
        //copy01();
        //基本字节流一次读写一个字节数组
        //copy02();
        //高效字节流一次读写一个字节
        //copy03();
        //高效字节流一次读写一个字节数组
        //copy04();
    }

    //基本字节流一次读写一个字节
    private static void copy01() throws IOException {
        FileInputStream fis = new FileInputStream("E:\video01.avi");
        FileOutputStream fos = new FileOutputStream("E:\video02.avi");
        int read = 0;
        while ((read = fis.read()) != -1) {
            fos.write(read);
        }
        fis.close();
        fos.close();
    }

    //基本字节流一次读写一个字节数组
    private static void copy02() throws IOException {
        FileInputStream fis = new FileInputStream("E:\video01.avi");
        FileOutputStream fos = new FileOutputStream("E:\video02.avi");
        byte[] bytes = new byte[1024 * 8];
        int readLen = 0;
        while ((readLen = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, readLen);
        }
        fis.close();
        fos.close();
    }

    //高效字节流一次读写一个字节
    private static void copy03() throws IOException {

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\video01.avi"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\video02.avi"));
        int read = 0;
        while ((read = bis.read()) != -1) {
            bos.write(read);
        }
        bis.close();
        bos.close();
    }

    //高效字节流一次读写一个字节数组
    private static void copy04() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\video01.avi"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\video02.avi"));
        byte[] bytes = new byte[1024 * 8];
        int readLen = 0;
        while ((readLen = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, readLen);
        }
        bis.close();
        bos.close();
    }
}

字符流
只能读写文本文件
出现的原因
	由于字节流操作中文不方便 java就提供了字符流
编码和解码
	编码:
		就是把字符串转换成字节数组
		把看得懂的变成看不懂的
		String -- byte[]
	解码:
		把字节数组转换成字符串
		把看不懂的变成看得懂的
		byte[] -- String
		
	public byte[] getBytes()
	使用平台的默认字符集将此String编码为byte序列 并将结果存储到一个新的byte数组中 
	public byte[] getBytes(String charsetName)
	使用指定的字符集将此String编码为byte序列 并将结果存储到一个新的 byte数组中

FileReader
FileReader(File file) 
创建一个新的FileReader 给予File读  
FileReader(String fileName) 
创建一个新的FileReader 给定要读取的文件的名称  

FileWriter
FileWriter(File file) 
构建了一个文件对象FileWriter对象 
FileWriter(File file, boolean append) 
构建了一个文件对象FileWriter对象 指示是否附加写入的数据 
FileWriter(String fileName) 
构造给定文件名的FileWriter对象。  
FileWriter(String fileName, boolean append) 
构造FileWriter对象给出一个文件名与一个布尔值 指示是否附加写入的数据 


字符缓冲流
BufferedReader
BufferedReader(Reader in) 
创建一个使用默认大小输入缓冲区的缓冲字符输入流 
BufferedReader(Reader in, int sz) 
创建一个使用指定大小的输入缓冲区的缓冲字符输入流 
public String readLine() 
读一行文本

BufferedWriter
BufferedWriter(Writer out) 
创建一个使用默认大小输出缓冲区的缓冲字符输出流 
BufferedWriter(Writer out, int sz) 
创建一个新的缓冲字符输出流,该流使用给定大小的输出缓冲区 
public void newLine()
写行分隔符
public void flush() 
冲流 

转换流
InputStreamReader
字节输入流的数据转换为字符流
public InputStreamReader(InputStream in) 
创建一个inputstreamreader使用默认字符集
public InputStreamReader(InputStream in,String charsetName) 
创建一个inputstreamreader使用指定的字符集
public int read() 
一次读取一个字符 如果没有读到 返回-1
public int read(char[] cbuf) 
一次读取一个字符数组 如果没有读到 返回-1

OutputStreamWriter
字节输出流的数据转换为字符流
public OutputStreamWriter(OutputStream out) 
创建一个outputstreamwriter使用默认的字符编码。 
public OutputStreamWriter(OutputStream out,String charsetName) 
创建一个outputstreamwriter使用指定的字符集
把字节流数据转换为字符流
public void write(int c) 
写一个字符
public void write(char[] cbuf) 
写一个字符数组
public void write(char[] cbuf,int off,int len) 
写一个字符数组的 一部分
public void write(String str) 
写一个字符串
public void write(String str,int off,int len) 
写一个字符串的一部分
public void flush()
冲流

集合与流 ArrayList
public class ArrayListMyTest {
    public static void main(String[] args) throws IOException {
        
        ArrayList list = new ArrayList<>();
        list.add("jack");
        list.add("tom");
        list.add("king");
        list.add("smith");
        //把集合中的数据存储到文件中
        //遍历集合,把数据写到文件中

        BufferedWriter writer = new BufferedWriter(new FileWriter("E:\Me.txt"));
        list.forEach(new Consumer() {
            @Override
            public void accept(String s) {
                try {
                    writer.write(s);
                    writer.newLine();
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        writer.close();
    }
}
LinkedHashMap
public class LinkedHashMapWriter {
    public static void main(String[] args) throws IOException {
     
        LinkedHashMap hashMap = new LinkedHashMap<>();
        hashMap.put("username", "king");
        hashMap.put("password", "123456");
        hashMap.put("email", "nebual@163.com");
        hashMap.put("phone", "13910733521");
        Set keySet = hashMap.keySet();

        BufferedWriter writer = new BufferedWriter(new FileWriter("user.txt"));
        for (String s : keySet) {
            writer.write(s + "=" + hashMap.get(s));
            writer.newLine();
            writer.flush();
        }
        writer.close();
    }
}

public class LinkedHashMapReader {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("user.txt"));
        LinkedHashMap hashMap = new LinkedHashMap<>();
        String s;
        while ((s = reader.readLine()) != null) {
            String[] split = s.split("=");
            hashMap.put(split[0], split[1]);
        }
        Set keySet = hashMap.keySet();
        for (String key : keySet) {
            System.out.println(key + "=" + hashMap.get(key));
        }
        reader.close();
    }
}

内存操作流
概述
	a:操作字节数组
		ByteArrayOutputStream
		ByteArrayInputStream
		此流关闭无效,所以无需关闭
	b:操作字符数组
		CharArrayWrite
		CharArrayReader
	c:操作字符串
		StringWriter
		StringReader		
歌曲串烧
public class ByteArrayInputStreamAOut {
    public static void main(String[] args) throws IOException {
        //把几个歌曲串烧在一起
        FileInputStream in = null;
        byte[] bytes = new byte[1024 * 8];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        File file = new File("E:\Test");
        File[] files = file.listFiles();
        int readLen = 0;
        for (File f : files) {
            in = new FileInputStream("E:\Test\" + f.getName());
            while ((readLen = in.read(bytes)) != -1) {
                bos.write(bytes,0,readLen);
            }
        }
        FileOutputStream out = new FileOutputStream("E:\Demo\a.mp3");
        byte[] b = bos.toByteArray();
        int len = 0;
        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        while ((len=bis.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
        in.close();
        bos.close();
        bis.close();
        out.close();
    }
}

打印流
PrintWriter
概述
	a:打印流只能操作目的地,不能操作数据源(不能进行读取数据)
	b:可以操作任意数据类型的数据 调用print()方法可以写任意数据类型
	c:如果我们启用自动刷新,那么在调用println、printf或format方法中的一个方法的时候,会完成自动刷新
实现自动刷新和换行
打印流只能进行写数据,不能进行读取数据

PrintWriter
PrintWriter(OutputStream out, boolean autoFlush) 
创建从现有的OutputStream新PrintWriter实现自动刷新和换行
PrintWriter(Writer out, boolean autoFlush) 
创建一个新的PrintWriter 实现自动刷新和换行
public void print(String s) 
打印一个字符串
public void println(String x)
打印一个字符串 然后终止行

标准输入输出流
标准输入输出流概述
在System这个类中存在两个静态的成员变量
public static final InputStream in
标准输入流, 对应的设备是键盘
public static final PrintStream out
标准输出流,对应的设备就是显示器
System.in的类型是InputStream.
System.out的类型是PrintStream是OutputStream的孙子类
二种方式实现键盘录入
A.Scanner sc = new Scanner(System.in);
B.BufferedReader的readLine方法
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

随机访问流
RandomAccessFile类不属于流,是Object类的子类
通过getFilePointer方法获取文件指针,并且可以通过seek方法设置文件指针

序列化流 反序列化流
序列化流: ObjectOutputStream
    序列化:就是把对象通过流的方式存储到文件中
    序列化:把对象转换为字节序列的过程称为对象的序列化
    注意: 此对象 要重写Serializable接口才能被序列化
反序列化流: ObjectInputStream
	反序列化:就是把文件中存储的对象以流的方式还原成对象
	反序列化:把字节序列恢复为对象的过程称为对象的反序列化

解决序列化时候的黄色警告线问题
	如果不显示指定serialVersionUID,JVM在序列化时会根据属性自动生成一个serialVersionUID,然后与属性一起序列化,再进行持久化或网络传输
	在反序列化时,JVM会再根据属性自动生成一个新serialVersionUID, 然后将这个新版serialVersionUID与序列化时生成的serialVersionUID进行比较,如果相同则反序列化成功,否则报错
	在实际开发中,都会显示指定一个serialVersionUID
	
让对象的成员变量不被序列化
    使用transient关键字声明不需要序列化的成员变量
    private transient int age;
    可以阻止成员变量的序列化使用transient
    注意:静态变量也不会序列化 因为序列化是针对对象而言的 而static属性优先于对象存在 随着类的加载而加载 所以不会被序列化
 
ObjectInputStream
public final Object readObject()
从对象输入流对象   

ObjectOutputStream
public final void writeObject(Object obj)
写入指定的对象的对象 
对象存取
public class Homework02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //通过序列化流与反序列化流完成从file.txt文件存取对象的操作
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt"));
        out.writeObject(new Student("jack", 15));
        out.writeObject(new Student("tom", 16));
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt"));
        Student s1 = (Student) in.readObject();
        System.out.println(s1);
        Student s2 = (Student) in.readObject();
        System.out.println(s2);
        in.close();
    }
}

class Student implements Serializable {
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}

Properties(双列集合)
Properties作为Map集合的使用
Properties父类是Hashtable
Properties不能指定泛型
属性列表中每个键及其对应值都是一个字符串

Properties
public Object setProperty(String key, String value) 
调用方法 put Hashtable
public String getProperty(String key)	
在这个属性列表中搜索指定的键的属性
public Set stringPropertyNames()
在这个属性列表中返回一组键,其中键和它的对应值是字符串,包括在默认属性列表中的不同键,如果同一个名称的一个键没有从主要属性列表中找到
public void load(Reader reader) 
从一个简单的行导向格式中读取输入字符流中的属性列表(键和元素对)
public void load(InputStream inStream) 
从输入字节流中读取属性列表(键和元素对)
public void store(OutputStream out,String comments) 
写这个属性列表(关键元素对)在这Properties表格式来合适的输出流加载到一个Properties表使用load(InputStream)方法。
public void store(Writer writer,String comments) 
写这个属性列表(关键元素对在这 Properties表格式来合适的输出字符流使用load(Reader)方法
修改键值对
public class SetValue {
    public static void main(String[] args) throws IOException {
        //需求:我有一个文本文件,我知道数据是键值对形式的,但是不知道内容是什么。
        //请写一个程序判断是否有"lisi"这样的键存在,如果有就改变其值为"100"
        Properties properties = new Properties();
        properties.load(new FileReader("nameAge.properties"));
        properties.forEach(new BiConsumer() {
            @Override
            public void accept(Object o, Object o2) {
                String key = (String) o;
                if ("lisi".equals(key)){
                    properties.setProperty("lisi","100");
                }
            }
        });
        properties.store(new FileWriter("nameAge.properties"),null);
    }
}

SequenceInputStream
a:构造方法
	SequenceInputStream(InputStream s1, InputStream s2) 
	通过记住这两个参数来初始化新创建的 SequenceInputStream(将按顺序读取这两个参数 先读取s1 然后读取 s2)
	以提供从此SequenceInputStream读取的字节。
b:构造方法
	SequenceInputStream(Enumeration e) 
	通过记住参数来初始化新创建的SequenceInputStream 该参数必须是生成运行时类型为InputStream对象的Enumeration型参数
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970404.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号