千峰java逆战班Day31

本文深入讲解Java中的IO流操作,包括字节流、字符流、缓冲流、序列化等核心概念,以及如何使用这些流进行文件读写、复制和序列化对象。

Day31

*File.separator : 分隔符(\)

*通过byte数组进行读取和写入

public static void m2(File file) throws IOException{
    InputStream is = new FileInputStream(file);
    
    byte[] b = new byte[4];
    int count = -1;
    //·返回读取到了多少个元素,如果没有读取到返回-1
    while((count = is.read(b)) != -1){
        for(int i = 0; i < count; i++){
            System.out.println((char)b[i]);
        }
	}
}

*同时使用输入和输出流,实现奖一个文件中的内容读取出来,添加上新的信息,再写入。

import java.io.*;

public class TestPutAndOut {

	public static void main(String[] args) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try {
			//·同一个文件对象,不能同时有输入和输出流(流是单向的)。
			fis = new FileInputStream("test.txt");
			//·读取文件内容
			byte[] b = new byte[1024];
			//·返回读取的个数,并保存在count中
			int count = fis.read(b);
			String str = new String(b,0,count);
			//·再写入内容
			fos = new FileOutputStream("test.txt");
			fos.write((str+"哈哈哈哈").getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//·关闭流
			CloseStream.close(fis);
			CloseStream.close(fos);
		}
	}
}

*使用输入和输出流,复制一个jpg文件。

import java.io.*;

public class TestCopyImage {

	public static void main(String[] args) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			//·输入流在读取时,如果没有该文件会出现FileNotFoundException
			fis = new FileInputStream("test1.jpg");
			//·输出流在写入时,如果没有该文件则会创建该文件,但是不会自动创建文件夹
			fos = new FileOutputStream("a.jpg");
			int result = -1;
			//·循环读取test1.jpg之后写入a.jpg
			while ((result = fis.read()) != -1) {
				fos.write(result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//·关闭流
			CloseStream.close(fis);
			CloseStream.close(fos);
		}
	}
}

*输入流和输出流:

输入: 字节流:FileInputStream / BufferedInputStream(带缓冲区)

​ 字符流:FileRead / BufferedRead(带缓冲区)

输出: 字节流:FileOutputStream / BufferedOutputStream(带缓冲区)

​ 字符流:FileWriter / BufferedWriter(带缓冲区)

字节流用于二进制数据的输入和输出;字符流用于文本文档的输入和输出

*缓冲流:BufferedInputStream、BufferedOutputStream

import java.io.*;

public class TestBuffered {

	public static void main(String[] args) throws IOException {
		OutputStream is = new FileOutputStream("test.txt");
		BufferedOutputStream bos = new BufferedOutputStream(is);
		//·调用write方法时,写入的值是保存在缓冲区(数组)当中的
		bos.write('a');
		bos.write('b');
		bos.write('c');
		//·调用flush方法,讲缓冲区中的值一次性写入到文件中。
		bos.flush();
		//·关闭这个缓冲流时,会自动调用flush方法。
		bos.close();
	}
}

​ 比较使用缓冲区和不适用缓冲区的效率:使用缓冲区效率明显提高

package com.qianfeng.pm;

import java.io.*;

import com.qianfeng.am.CloseStream;

public class TestBufferedCopyImage {

	public static void main(String[] args) {
		BufferedInputStream fis = null;
		BufferedOutputStream fos = null;
		try {
			//·Buffered是一个包装类,传入一个file对象。
			fis = new BufferedInputStream(new FileInputStream("test.MP4"));
			fos = new BufferedOutputStream(new FileOutputStream("copy\\test.MP4"));
			int result = -1;
			//·循环读取test1.jpg之后写入a.jpg
			while ((result = fis.read()) != -1) {
				fos.write(result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//·关闭流
			CloseStream.close(fis);
			CloseStream.close(fos);
		}
	}
}

*字符输入和输出流:FileReader extends InputStreamReader(FileReader里面没有自己的方法,所以这两个都是字符输入流),字符输出流同理。

​ 从使用上来说,和字节输入输出流没有区别

import java.io.*;
import com.qianfeng.am.CloseStream;

public class TestFileRead {

	public static void main(String[] args) {
		FileReader fis = null;
		try {
			fis = new FileReader("test.txt");
			int result = -1;
			while((result = fis.read()) != -1) {
				System.out.print((char)result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			CloseStream.close(fis);
		}
	}
}

import java.io.*;
import com.qianfeng.am.CloseStream;

public class TestFileWriter {

	public static void main(String[] args) {
		FileWriter fis = null;
		try {
			fis = new FileWriter("test.txt",true);//·追加写入
			//·调用write方法时,会在文件内容的后面追加写入
			fis.write("你好111");
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			CloseStream.close(fis);
		}
	}
}

​ 字符的缓冲流:

package com.qianfeng.pm;

import java.io.*;
import com.qianfeng.am.CloseStream;

/**
 * @author 吴一凡
 *	字符缓冲流的不同点:单一行读取和换行。
 */
public class TestBufferedReaderWriter {

	public static void main(String[] args) {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new FileReader("test.txt"));
			bw = new BufferedWriter(new FileWriter("testcopy.txt",true));
			//·只读取一行的信息
			String str = br.readLine();
			bw.write(str);
			bw.newLine();
			bw.write("使用字符缓冲流写入");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			CloseStream.close(bw);
			CloseStream.close(br);
		}
	}
}

​ 桥接器:字节流转换成字符流(InputStreamReader)

import java.io.InputStreamReader;
import java.util.Scanner;

public class TestScanner {

	public static void main(String[] args) {
		//·键盘录入
		Scanner scan = new Scanner(System.in);//·in 是一个字节输入流
		//·传入一个字节流给这个桥接器变成一个字符流
		InputStreamReader rd = new InputStreamReader(System.in);
	}
}

*使用IO流时的编码问题:使用getBytes()方法进行编码,用String(str, “编码方式”)

import java.io.UnsupportedEncodingException;

public class TestEncoding {

	public static void main(String[] args) throws UnsupportedEncodingException {
		String s1 = "你好世界";
		//·UTF-8文本转二进制。编码
		byte[] b = s1.getBytes("UTF-8");
		//·二进制转UTF-8文本。解码
		String s2 = new String(b, "UTF-8");
		System.out.println(s2);
	}
}

*序列化:

	package com.qianfeng.pre.demo1;

import java.io.*;

import com.qianfeng.am.CloseStream;

/**
 * @author 吴一凡
 *	将数据写入文件,而不是文本。
 */
public class TestObjectStream {

	public static void main(String[] args) throws Exception{
		OutputStream os = new FileOutputStream("Files\\object.txt");
		ObjectOutputStream oos = new ObjectOutputStream(os);
		//·将该对象写入文件。
		oos.writeObject(new Student("张三", 6, new Adrress("安徽","2310000")));
		oos.writeObject(new Student("李四", 7, new Adrress("安徽","2310000")));
		oos.writeObject(new Student("王五", 8, new Adrress("安徽","2310000")));
		oos.writeObject(new Student("赵六", 9, new Adrress("安徽","2310000")));
		oos.close();
		
		InputStream is = new FileInputStream("Files\\object.txt");
		ObjectInputStream ois = new ObjectInputStream(is);
		while (true) {
			//·读取数据
			try {
				Student stu = (Student) ois.readObject();
				System.out.println(stu);
			} catch (EOFException e) {
				break;
			}finally {
				//·在关闭被包装的流时,只需要关闭最外层的包装流,里面的自动关闭
				CloseStream.close(ois);
				CloseStream.close(os);
			}
		}
	}
}


/**
 * @author 吴一凡
 *	序列化;
 *	必须实现serializable接口
 *	序列化一个对象时,必须保证对象的所有属性都是可序列化的
 *	transient修饰为临时属性,不会被序列化
 *	读取到文件的尾部标志:java.io.EOFException
 */
class Student implements Serializable{
	String name;
	Integer age;
	Adrress addr;
	public Student() {
	}
	public Student(String name, Integer age, Adrress addr) {
		super();
		this.name = name;
		this.age = age;
		this.addr = addr;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", addr=" + addr + "]";
	}
}

class Adrress implements Serializable{
	//·
	transient String position;
	String zipCode;
	
	public Adrress() {
	}
	
	public Adrress(String position, String zipCode) {
		super();
		this.position = position;
		this.zipCode = zipCode;
	}

	@Override
	public String toString() {
		return "Adrress [position=" + position + ", zipCode=" + zipCode + "]";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值