java之IO流

I/O流详细介绍:https://www.cnblogs.com/wugongzi/p/12092326.html
缓冲流:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter
加速读写,原理:缓冲流把数据从原始流成块读入或把数据积累到一个大数据块后再成批写出,通过减少资源的读写次数来加快程序的执行。
关闭缓冲流会自动关闭其中的输入输出流,不需要再重复关闭。

ObjectInputStream(反序列化)和ObjectOutputStream(序列化)说明:
1、主要用于基本数据类型和对象的处理流。
2、不能序列化static和transient修饰的成员变量。
3、要序列化的类需要继承Serializable接口或者Externalizable接口。
4、要序列化的类需要添加 序列版本号,不加默认会生成一个,但修改类后这个值就会改变,导致之前的对象不能被反序列化回来。
序列版本号:private static final long serialVersionUID = 123456789L;
5、要序列化的类中的所有属性也都需要是可序列化的。

/*
 * 继承 Serializable 才可序列化
 */
class Student implements Serializable {
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", address=" + address + "]";
	}

	// 序列版本号
	private static final long serialVersionUID = 123456789L;
	public String name;
	public int age;
	public transient String address;

	public Student(String name, int age, String address) {
		super();
		this.name = name;
		this.age = age;
		this.address = address;
	}

}

/*
	 * 反序列化
	 */
	@Test
	public void objStreamTest2()
	{
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream("stu.txt"));
			// 要按照写的顺序读
			Student sr1 =(Student) ois.readObject();
			Student sr2 =(Student) ois.readObject();
			System.out.println(sr1.toString());
			System.out.println(sr2.toString());
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (ois != null) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/*
	 * 序列化
	 */
	@Test
	public void objStreamTest() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream("stu.txt"));
			Student s1 = new Student("张三", 23, "上海虹北公寓58号楼101室");
			Student s2 = new Student("jay", 30, "上海虹北公寓58号楼201室");
			oos.writeObject(s1);
			oos.writeObject(s2);
			oos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (oos != null) {
					oos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

RandomAccessFile简介与使用:https://blog.csdn.net/qq_31615049/article/details/88562892
1、seek:指定文件的光标位置,从0开始,读写文件时从该位置读取。
2、getFilePointer:返回当前的文件光标位置。
3、length:文件的长度。
4、read()、read(byte[] b)、read(byte[] b,int off,int len)这些方法跟FileInputStream中的方法一样。
5、常用:readDouble() readFloat() readBoolean() readInt() readLong() readShort() readByte() readChar()
writeDouble() writeFloat() writeBoolean() writeInt() writeLong() writeShort() writeByte() writeChar()
6、readFully(byte[] b):这个方法的作用就是将文本中的内容填满这个缓冲区b。如果缓冲b不能被填满,那么读取流的过程将被阻塞,如果发现是流的结尾,那么会抛出异常。这个过程就比较像“凑齐一车人在发车,不然不走”。
7、getChannel:它返回的就是nio通信中的file的唯一channel。
8、skipBytes(int n):跳过n字节的位置,相对于当前的point。
9、读写方式:RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"), "rw");
r 以只读的方式打开文本,也就意味着不能用write来操作文件
rw 读操作和写操作都是允许的
rws 每当进行写操作,同步的刷新到磁盘,刷新内容和元数据
rwd 每当进行写操作,同步的刷新到磁盘,刷新内容
10、RandomAccessFile写文件时会覆盖原来的内容,要实现插入内容时,需要定位光标,读取光标后面的所有内容,拼接到要插入的内容后,然后写入。

RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
		raf1.seek(3);// 把指针定位到第4个字符
		// 避免乱码
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[20];
		int len;
		while ((len = raf1.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		raf1.seek(3);
		raf1.write("xxx".getBytes());
		raf1.write(baos.toString().getBytes());
		baos.close();
		raf1.close();

11、RandomAccessFile既可以做输入流,也可以做输出流。作为输出流时,如果文件不存在,则创建文件,如果文件存在则覆盖文件。
示例代码:

/*
	 * 随机访问文件,可读可写
	 */
	@Test
	public void randomAccessFileTest() {
		RandomAccessFile raf1 = null;
		ByteArrayOutputStream baos = null;
		try {
			raf1 = new RandomAccessFile("1.txt", "rw");
			raf1.seek(3);// 把指针定位到第4个位置
			// 避免乱码
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[20];
			int len;
			while ((len = raf1.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			raf1.seek(3);
			raf1.write("xxx".getBytes());
			raf1.write(baos.toString().getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (raf1 != null) {
					raf1.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * 字节流读写文件,缓冲流,加速读写
	 */
	@Test
	public void fileStreamTest() {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			File file1 = new File("1.txt");
			File file2 = new File("2.txt");

			bis = new BufferedInputStream(new FileInputStream(file1));
			bos = new BufferedOutputStream(new FileOutputStream(file2));

			byte[] buffer = new byte[20];
			int len;
			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * 字符流,读文件,没有会报错
	 */
	@Test
	public void fileReaderTest() {
		FileReader fr = null;
		try {
			File file1 = new File("1.txt");
			char[] cbuf = new char[6];
			int len;
			fr = new FileReader(file1);
			while ((len = fr.read(cbuf)) != -1) {
				String str = new String(cbuf, 0, len);
				System.out.print(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null) {
					fr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * 字符流,写文件,没有会创建
	 */
	@Test
	public void fileWriterTest() {
		FileWriter fw = null;
		try {
			File file1 = new File("1.txt");
			fw = new FileWriter(file1, false);
			fw.write("你好,这是测试数据1。
");
			fw.write("你好,这是测试数据2。
");
			fw.append("你好,这是测试数据3。
");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fw != null) {
					fw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

xxx

原文地址:https://www.cnblogs.com/xsj1989/p/14917446.html