java基础--IO流

本文深入讲解Java IO流的基础概念,包括字节流、字符流、输入流和输出流的使用方法,以及节点流和处理流的区别。同时,探讨了如何利用File类进行文件操作,并介绍了序列化和反序列化的实现过程。

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

IO

File
file:
	抽象的路径以及文件
1.创建对象是无须注意当前路径或者是文件是否存在,都会创建出来
2. 和平台无关的路径分隔符
	File.pathSeparator 路径结束符
	File.separator 		路径分割符
常见方法:
	File  f  = new File();
	f.canExecute()查看是否可执行	f.canRead()	是否可读
	f.createNewFile()创建文件是否成功
	f.getAbsolutePath()获取绝对路径	f.getPath()获取相对路径
	f.getName()获取文件名	f.getTotalSpace()获取总共大小
	getusableSpace()获取可用大小
mkdir和mkdirs的区别:
	前者只能创建一级目录,后者可以创建多级目录
io
为什么需要io?
	1.file类本身只能针对文件或者是目录的元数据(除了内容本身)进行操		作,不能对文件中的内容做任何操作
	2. 截至目前为止,我们存储的手段是很也有限,以及有问题的。
		学习过的存储手段:
			变量	对象	数组--》存储都是在内存中的--》程序启动之后数据存在;程序销毁时数据丢失
		但是在后期整个编码,项目的过程中我们对于数据一定要持久的存储起来,方便后期使用以及更新
	3.无法将数据持久存储起来
解决办法:
	通过IO流的知识,将数据写入到文件中,或者读取文件中数据信息。文件是存储在磁盘上的,电脑关机之后,数据还在。

io(input/output):

图片

IO流的分类
1.按照输出的数据类型不同:
	字节流	字节输入、输出流
	字符流	字符输入、输出流
2. 按照流的方向:
	输入流输出流
3. 按照处理功能:
	节点流
	处理流
节点流和处理流

图片

///下面	Writer out = new OutputStreamWriter(os);为处理流
//	OutputStream os = new FileOutputStream("a.txt");和
//  BufferedWriter bw = new BufferedWriter(out);为节点流


public class Test05 {
	public static void main(String[] args) throws IOException {
		
		//创建对象
		OutputStream os = new FileOutputStream("a.txt");
		
		Writer out = new OutputStreamWriter(os);
		
		BufferedWriter bw = new BufferedWriter(out);
		
		
		//写出数据
		bw.write("我自横刀向天笑");
		bw.newLine();
		bw.write("去留肝胆两昆仑");
		
		
		bw.flush();
		
		bw.close();
		out.close();
		os.close();
	}
}
InputStream
FileInputStream
读取数据:
	字节流:InputStream  是所有字节流的父类
	输入:
	子类:
		FileInputStream文件字节输入流,数据源在文件中,读取按照字		节读取,流的方向的输入
循环读取:
	每次读取数据时,只能读一个字节,在通过read方法读取时如果读到文件末尾,返回-1。循环读取时FileInputStream要保证文件存在
	
public static void main(String[] args) throws IOException { //1:创建对象 
InputStream is = new FileInputStream("C:\\Users\\wawjy\\Desktop\\cc.txt");
    int num = 0;
//2:读取数据
while((num=is.read())!=-1) {
//3:分析数据
System.out.println("读取数据:"+num);
}
//4:关闭资源
is.close();
}

读取多个字节

一次性读取一个字节数组
	public static void main(String[] args) throws IOException { 
	//声明对象
    InputStream is = new FileInputStream("C:\\Users\\wawjy\\Desktop\\cc.txt");
    //读取数据 
    //声明一个字节数组 
    byte[] buf = new byte[1024]; 
    //读取一个字节数组长度的数据 返回读取到的字节数组的长度
    int len = is.read(buf);
    //会将数据读取到buf中 
    //分析数据 
    String msg = new String(buf,0,len); System.out.println(msg); 
    //关闭资源 
    is.close(); 
    }

处理异常

package com.mage.Io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Test {
	public static void main(String[] args) {
		InputStream is=null;
		try {
			is = new FileInputStream("C:\\aa.txt");
			byte[] buf = new byte[1024];
			int len = is.read(buf);
			String msg = new String(buf,0,len);
			System.out.println(msg);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

ObjectInputStream
package com.mage.Io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Test01 {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		//创建对象
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
		//读取数据
		int num = ois.readInt();
		//输出数据
		System.out.println(num);
		//读取数据
		double d = ois.readDouble();
		//输出数据
		System.out.println(d);
		//读取数据
		String s = ois.readUTF();
		//输出数据
		System.out.println(s);
		//关闭
		ois.close();
	}
}


OutputStream
FileOutputStream
字节输出流:
	所有字节输出流的父类
	子类是FileOutputStream,输出的目的地是文件,输出的类型是字节
	输出时,如果文件不存在会创建该文件,但是不会创建不存在的目录

写出多个字符
创建FileOutputStream对象时,第二个参数为boolean,说明是否要在文件后追加内容,默认是false不追加

public static void main(String[] args) throws IOException { 
//创建对象 
OutputStream os = new FileOutputStream("aaa.a",true); 
//声明写出的数据
String msg = "laoxuezhideniyongyou"; 
//写出数据
os.write(msg.getBytes(),0,10); //10代表长度
//关闭资源 
os.close();
}

序列化和反序列化
(要用到ObjectInputStream,ObjectOutputStream)
对象的输出流将指定的对象写入到文件的过程,就是将对象序列化的过程,对象的输入流将指定序列化好的文件读出来的过程,就是对象反序列化的过程

将对象序列化
package com.mage.Io.outputstream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test {
	public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException {
		write();
		read();
		
	}
	
	public static void write() throws FileNotFoundException, IOException {
		//创建对象
		User u =new User("linzhengaugn",1,22);
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("aa.txt"));
		
		//写入数据
		oos.writeObject(u);
		
		
		//刷新并关闭资源
		oos.flush();
		oos.close();
	}
	public static void read() throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("aa.txt"));
		Object obj = ois.readObject();
		System.out.println(obj);
		ois.close();
	}
	
	
}
class User implements Serializable{
	private String name;
	private int gender;
	private int age;
	public User() {
		
		
	}
	public User(String name,int gender,int age) {
		super();
		this.name = name;
		this.gender=gender;
		this.age = age;
		
		
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getGender() {
		return gender;
	}
	public void setGender(int gender) {
		this.gender = gender;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "User [name=" + name + ", gender=" + gender + ", age=" + age + "]";
	}
	
	
}


结果(控制台和文件aa.txt的输出)

图片

图片

若在上述代码中加入transient(在序列化的时候不会将当前属性对应的值序列化出去,将值变为默认值)

class User implements Serializable{
	private transient String name;
	private int gender;
	private transient int age;
	public User() {
		
		
	}

结果

[外链图片转存失败(img-wFvbj67n-1564294124716)(https://i.loli.net/2019/07/27/5d3be95251d5714824.png)]

序列化id

在序列化的时候记得增加序列化版本号,保证输出是修改之后,读取不会报错
	class User implements Serializable{
	//序列化id
	private static final long serialversionUID = 1L;
	private String name;
	private int gender;
	private int age;

对于单例的影响
当程序在序列化的时候会默认调用类中的readResolve方法,如果不重写该方法,导致每次返回的是一个当前类的对象的副本,这个副本是一个新对象,导致破坏单例模式。

package com.mage.Io;

import java.io.Serializable;

public class Lazy implements Serializable{
	private static Lazy lazy = null;
	private Lazy() {
		
	}
	public static Lazy getInstance() {
		if(lazy==null) {
			new Lazy();
		}
		return lazy;
	}
	public Object readResolve() {
		
		return lazy;
	}
}


复制粘贴
public static void CtrlCV(String srcFile,String destFile) throws IOException{
    /*
    //1:声明复制和粘贴的文件对象 
    String srcFile = "C:\\Users\\wawjy\\Desktop\\1.jpg"; 
    String destFile = "123.jpg";
    */
    //2:声明对象
    InputStream is = new FileInputStream(srcFile); 		       OutputStream os = new FileOutputStream(destFile); 
    //3:读取文件 
    int len = 0; while((len=is.read())!=-1) {
        //写出 
        os.write(len); 
    }
    os.close();
    is.close();
}

Reader
InputStreamReader
public class Test03 {
	public static void main(String[] args) throws FileNotFoundException,IOException{
		//创建对象
		InputStream is = new FileInputStream("a.txt");
		Reader r = new InputStreamReader(is);
		//指定字符集合
		//Reader reader = new InputStreamReader(new FileInputStream("c.txt"),"utf-8");
		//读取
		char[] chs = new char[1024];
		int count = r.read(chs);
		//分析结果
		System.out.print(new String(chs,0,count));
		//关闭资源
		r.close();
		is.close();
	}
}

BufferedReader(效率更高)

创建对象和Reader一样的用法,要用到StringBuilder

public class Test02 {
	public static void main(String[] args) throws IOException {
	
		//创建对象和Reader一样的用法
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(
				new FileInputStream("a.txt")));
		
		//读取
		String str = null;
		StringBuilder sb = new StringBuilder();
		while((str=reader.readLine())!=null) {
			sb.append(str);
			sb.append("\r\n");
			
		}
		System.out.println(sb.toString());
		//关闭资源
		reader.close();
	}
}

Writer
public class Test02 {
	public static void main(String[] args) throws IOException {
		
		//创建对象
		Writer out = new OutputStreamWriter(new FileOutputStream("a.txt"));
		
		//声明输出数据
		String str = "你a好a";
		
		//输出
		//out.write(str.toCharArray());
		out.write(str);
		
		//刷新
		out.flush();
		
		//关闭
		out.close();
		
	}
}

BufferedWriter
public class Test05 {
	public static void main(String[] args) throws IOException {
		
		//创建对象
		OutputStream os = new FileOutputStream("a.txt");
		
		Writer out = new OutputStreamWriter(os);
		
		BufferedWriter bw = new BufferedWriter(out);
		
		
		//写出数据
		bw.write("我自横刀向天笑");
		bw.newLine();
		bw.write("去留肝胆两昆仑");
		
		
		bw.flush();
		
		bw.close();
		out.close();
		os.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值