IO流知识点整理后续

本文详细介绍了Java中的IO流,包括基本数据类型流、万能输出打印流PrintWriter/PrintStream、输入输出流、RandomAccessFile随机访问文件、序列化流、反序列化流和Properties属性集的使用。重点讲解了各类流的特点和典型应用场景,并给出了相关代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本数据类型流

基本数据类型流可以读写基本数据类型

数据输入流:DataInputStream
DataInputStream(InputStream in)
数据输出流:DataOutputStream
DataOutputStream(OutputStream out)

特点:

1.该流是一个字节流,可以读写字节的同时,还能够读写基本数据类型
2.通过数据类型输出流写入到文件中,使用文本文件打开是不能阅读,提高了基本数据类型在文件中保存的安全性
3.读的时候必须和写的顺序保持一致,提高了基本数据类型在文件中保存的安全性

public class OtherIoCode02 {

	public static void main(String[] args) throws IOException {
		write();
		read();
	}

	@SuppressWarnings("unused")
	private static void read() throws IOException {
		DataInputStream dis = new DataInputStream(new FileInputStream("dis.txt"));
		byte by = dis.readByte();
		short s = dis.readShort();
		int i = dis.readInt();
		long l = dis.readLong();
		char ch = dis.readChar();
		float f = dis.readFloat();
		double d = dis.readDouble();
		boolean b = dis.readBoolean();
		dis.close();

	}

	@SuppressWarnings("unused")
	private static void write() throws IOException {
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("dis.txt"));
		dos.writeByte(10);
		dos.writeShort(20);
		dos.writeInt(30);
		dos.writeLong(40);
		dos.writeChar('a');
		dos.writeFloat(2.5f);
		dos.writeDouble(3.5);
		dos.writeBoolean(true);
		dos.close();
	}

}

万能输出打印流PrintWriter/ PrintStream

概述:

向文本输出流打印对象的格式化表示形式。此类实现在 PrintStream 中的所有 print 方法。

特点:

1.只能写数据,不能读取数据。
2.可以操作任意类型的数据。
3.如果启动了自动刷新,能够自动刷新。
4.如果启用了自动刷新,则只有在调用 println、printf 或 format 的其中一个方法时才可能完成此操作

public class OtherIoCode01 {

	public static void main(String[] args) throws IOException {
		PrintWriter pw =new PrintWriter(new FileWriter("pt.txt"), true);
		pw.println("Hello");
		pw.println("World");
		pw.println("世界你好");
		pw.println("good");
		pw.println("morning");
		pw.format("我叫做%s,我今年%d岁", "张三",20);
		pw.close();
        
      //copy("test.txt", "demo.txt");
	}
	private static void copy(String srcFileName, String descFileName) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(srcFileName));
		PrintWriter pw = new PrintWriter(new FileWriter(descFileName), true);
		
		String line = null;
		while ((line = br.readLine()) != null) {
			pw.println(line);
		}
		
		br.close();
		pw.close();
	}
}

模拟记录用户登录日志(采用追加方式记录),从控制台接收用户输入的用户名和密码,在文件中记录用户名和密码以及登录时间。
格式如下:
name=zhangsan
pwd=123456
time=2019-05-06 16:22:33

public class OtherIoDemo01 {

	public static void main(String[] args) throws IOException {
		Scanner input = new Scanner(System.in);
		System.out.println("请输入用户名:");
		String userName = input.next();
		System.out.println("请输入密码:");
		String password = input.next();
		System.out.println("请选择是否登录?(Y/N)");
		String yesOrNo = input.next();
		if ("Y".equals(yesOrNo)) {
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateStr = sdf.format(d);

			PrintWriter pw = new PrintWriter(new FileWriter("userInfo.txt", true));
			pw.println("name=" + userName);
			pw.println("pwd=" + password);
			pw.print("time=" + dateStr);
			pw.close();

			System.out.println("登录成功");
			System.out.println("登录的时间:"+dateStr);
		} else {
			System.out.println("登录失败!!!");
		}
		input.close();
	}

}

输入输出流

System类中的静态变量:in,out 。
“标准”输入流:static InputStream in 。
“标准”输出流:static PrintStream out 。

它们各代表了系统标准的输入和输出设备。默认输入设备是键盘,输出设备是显示器。系统流不需要我们自己创建,直接使用即可

使用IO流编模拟Scanner键盘录入对象,代码如下:

public class IODemo04 {
	public static void main(String[] args) throws IOException {
//		InputStream is = System.in;
//		
//		System.out.println("请输入一个字节:");
//		int b = 0;
//		b = is.read(); // 这个read()方法是一个阻塞方法,会阻塞main方法,等待用户输入
//		System.out.println((char)b);
//		
//		b = is.read(); // 这个read()方法是一个阻塞方法,会阻塞main方法,等待用户输入
//		System.out.println((char)b);
		
//		Scanner input = new Scanner(System.in);
//		System.out.println("请输入字符串:");
//		String line = input.next();
//		System.out.println(line);
//		System.out.println("请输入小数:");
//		double d = input.nextDouble();
//		System.out.println(d);
		
		MyScanner input = new MyScanner(System.in);
		System.out.println("请输入一个字符串:");
		String line = input.next();
		System.out.println(line);
		
		System.out.println("请输入一个小数");
		double d = input.nextDouble();
		System.out.println("您输入的小数是:" + d);
		
	}
}

class MyScanner{
	private InputStream is; // System.in
	private BufferedReader br;
	
	public MyScanner() {}
	
	public MyScanner(InputStream is) {
		this.is = is;
	}
	
	public String next() throws IOException {
		return read();
	}

	public double nextDouble() throws IOException {
		double d = 0.0;
		try {
			d = Double.parseDouble(read());
		} catch (NumberFormatException nfe) {
			throw new InputMismatchException("哥们,你这要输入小数啊!!!一看你就不严谨!!!");
		}
		
		return d;
	}
	
	public String read() throws IOException {
		InputStreamReader isr = new InputStreamReader(is);
		String line = null;
		br = new BufferedReader(isr);
		line = br.readLine();
		return line;
	}
}

	

RandomAccessFile随机访问文件

概述:

此类的实例支持对随机访问文件的读取和写入。

特点:

1.RandomAccessFile类不属于流,是Object类的子类。

2.包含了InputStream和OutputStream的功能。

3.能够读写基本类型

4.支持对随机访问文件的读取和写入。 getFilePointer/seek

RandomAccessFile(String name, String mode)

long getFilePointer():获取文件指针

long length()

void seek(long pos):设置文件指针

void setLength(long newLength)

示例代码如下:

public class OtherIoCode03 {

	public static void main(String[] args) throws Exception {
		write();
		read();
	}

	@SuppressWarnings("unused")
	private static void write() throws Exception {
		RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
		raf.writeInt(100);
		raf.write("中国".getBytes());
		raf.close();
	}

	@SuppressWarnings("unused")
	private static void read() throws Exception {
		RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
		System.out.println(raf.length());
		raf.seek(4);
		byte[] by = new byte[10];
		int len = raf.read(by);
		System.out.println(new String(by, 0, len));
//		int i = raf.readInt();
//		System.out.println(i);
		System.out.println(raf.getFilePointer());
		raf.close();
	}
}

序列化流、反序列化流

序列化流ObjectOutputStream
反序列化流ObjectInputStream

1.ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream。可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。

2.如何实现序列化?
类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化,该接口没有任何方法,是一个标志接口。

3.未实现序列化抛出未序列化异常:NotSerializableException。

java.io.NotSerializableException
异常名称: 没有序列化异常
产生原因: 在将对象保存到文件系统的时候没有将对象实现序列化接口
解决方法: 针对需要写入到文件系统的对象实现对应的序列化接口

4.序列化数据后,再次修改类文件,读取数据会出问题,如何处理?

Exception in thread “main” java.io.InvalidClassException:
com.sxt.otherio.Person; local class incompatible:
stream classdesc serialVersionUID = -6469125083721773098,
local class serialVersionUID = 4687267829016438016

InvalidClassException: 无效类异常
产生原因: 文件中保存的流的序列化id和本地类文件的序列化id不匹配
解决办法: 保证id一致性

5.使用transient关键字声明不需要序列化的成员变量。
transient: 在将成员写入到文件的时候确保数据的安全,在反序列化的时候不能够获取到数据 。

示例代码如下:

public class OtherIoCode04 {

	public static void main(String[] args) throws Exception {
		write();
		read();
	}

	@SuppressWarnings("unused")
	private static void read() throws Exception {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
		Object obj = ois.readObject();
		if (obj instanceof Student) {
			Student s = (Student) obj;
			System.out.println(s.getName() + "|" + s.getAge());

		}

		ois.close();
	}

	@SuppressWarnings("unused")
	private static void write() throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
		oos.writeObject(new Student("张三", 20));
		oos.close();
	}

}



class Student implements Serializable {
	private static final long serialVersionUID = -7688038451403212881L;
	private String name;
	private transient Integer age;// 防止该成员变量序列化到文件中

	public Student() {
		super();
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "student [name=" + name + ", age=" + age + "]";
	}

}




Properties属性集

概述:

Properties 类表示了一个持久的属性集;Properties 可保存在流中或从流中加载;属性列表中每个键及其对应值都是一个字符串。Properties可以当做Map集合类使用

Properties的特殊遍历功能

public Object setProperty(String key,String value)
public String getProperty(String key)
public Set stringPropertyNames()

Properties和IO流结合使用

public void load(Reader reader)
public void store(Writer writer,String comments)

配置文件:

1.Properties 轻量级,在网络中传输带宽小,本地存储数据量简单,就是键值对结构,理解为一个类似于map的文件
2.XML 重量级,结构化清晰,可读性强,能够存储复杂结构的数据

持久化:

1.txt
2.Properties
3.XML
4.json
5.数据库

示例代码如下:

public class OtherIODemo01 {
	static Properties prop;
	static {
		prop = new Properties();
		try {
			prop.load(new FileReader("config/prop.properties"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws FileNotFoundException, IOException {
		// 当做map来使用
//		Properties prop = new Properties();
//		prop.put("hello1", "world1");
//		prop.put("hello2", "world2");
//		prop.put("hello3", "world3");
//		
//		Set<Object> keys = prop.keySet();
//		for (Object obj : keys) {
//			System.out.println(obj);
//		}
		
		// 当做特殊的属性集使用
		/*
		 *  public Object setProperty(String key,String value)
			public String getProperty(String key)
			public Set<String> stringPropertyNames()
		 */
//		Properties prop = new Properties();
//		prop.setProperty("hello1", "world1");
//		prop.setProperty("hello2", "world2");
//		prop.setProperty("hello3", "world3");
//		
//		Set<String> keys = prop.stringPropertyNames();
//		for (String key : keys) {
//			String value = prop.getProperty(key);
//			System.out.println(key + "=" + value);
//		}
		
		// 当做流使用
		/*
		 * Properties和IO流结合使用
			public void load(Reader reader)
			public void store(Writer writer,String comments)
		 */
//		System.out.println(prop);
		prop.store(new FileWriter("config/prop2.properties"), "comments");
	}
}

已知文本文件(userinfo.txt)如下图所示,数据是键值对形式的,请写一个程序判断是否有admin这样的用户存在,如果有就改变密码为“56789”

public class OtherIoDemo02 {

	public static void main(String[] args) {
		Properties properties=new Properties();
		try {
			properties.load(new FileReader("userinfo2.txt"));
			properties.store(new FileWriter("userInfo2.txt"), "comment");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Set<String> keys = properties.stringPropertyNames();
		for (String key : keys) {
			if (key.equals("admin")) {
				properties.setProperty("admin", "56789");
			}
		}
	}

				
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值