IO流

你若不想做,会找一个或无数个借口;你若想做,会想一个或无数个办法


本讲内容:文件流

     

一、File类(没有读写能力)

File类只用于表示文件(目录)的信息(名称、大小等),不能用于文件内容的访问
重要方法:
exists(): 判断文件/文件夹是否存在
delete():删除文件/文件夹
mkdir():创建文件夹
createNewFile():创建文件
separator():设置分隔符
isDirectory():是否是一个目录(文件夹),如果是目录返回true,如果不是目录or目录不存在返回false。
isFile():是否是一个文件
getAbsolutePath():获取绝对路径(E:\java\imooc)
getName():获取目录最后的名字(imooc)
getParent():获取父目录(E:\java)


二、RandomAccessFile类

RandomAccessFile 是java提供的对文件内容的访问,既可以读文件,也可以写文件。


三、IO流(输入流,输出流)

输入流:数据在文件到程序(内存)的路径

输出流:数据从程序(内存)到文件的路径

即:以内存为参照,如果数据向内存流动,则是输入流,反之是输出流。

1、字节流
InputStream:OutputStream这俩个是抽象类,这俩个子类分别为FileInputStream、FileOutputStream实现类
InputStream : 抽象了应用程序读取数据的方式
OutputStream:抽象了应用程序写出数据的方式

FileInputStream:具体实现了在文件上的读取数据

FileOutputStream:具体实现了向文件中写出byte数据的方法
输入流常用方法:
int b=in.read();读取一个字节无符号填充到int低八位。读到-1就读到结尾了。
in.read(byte[] buf);读取数据到字节数组buf
in.read(byte[] buf,int start,int size);读取数据到字节数组buf里,从buf的start位置开始存放size长度的数据。
输出流常用方法
out.write(int b)写出一个byte到流,b的低8柆
out.write(byte[] buf)将buf字节数组写入到流
out.write(byte[] buf,int start,int size)


四、扩展

1、DataInputStream/DataOutputStream对流功能的扩展,可以更加方便地读取int,long,字符等类型数据
writeInt()/writeDouble()/writeUTF()


2、BufferedInputStream/BufferedOutputStream
这俩个流类提供了带缓冲区的操作,一般打开文件进入写入或读取操作时,都会加上缓冲,这种流模式提高了IO的性能
FileOutputStream:write()方法相当于一滴一滴地把水转移到缸中(一个字节一个字节转移)
DataInputStream:writeXxx()方法相当于一瓢一瓢把水转移到缸中(int 四个字节转移过去)
BufferedOutputStream:write()方法相当于一瓢一瓢先放入桶中(缓冲区),现从桶中倒入到另一个缸中。


五、字符流

Reader 与InputStream类似都是抽象类

Writer 与OutputStream类似都是抽象类

InputStreamReader   完成byte流解析为char流,按照编码解析
OutputStreamWriter  提供char流到byte流,按照编码处理  

FileReader :FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数。所以FileReader只能按系统默认的字符集来解码

FileWriter :同上


 字符流的过滤器
 BufferedReader   ---->readLine 一次读一行
 BufferedWriter/PrintWriter   ---->写一行   


六、对象的序列化,反序列化

序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。

序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。
1)对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化 
2)序列化流(ObjectOutputStream)是过滤流----writeObject()方法
   反序列化流(ObjectInputStream)---readObject()方法
3)序列化接口(Serializable)
   对象必须实现序列化接口 ,才能进行序列化,否则将出现异常,这个接口,没有任何方法,只是一个标准


transient :关键字

private transient int age;  //该元素不会进行jvm默认的序列化,也可以自己完成这个元素的序列化


注意:

Flush() 是清空缓冲区数据,就是说你用读写流的时候,其实数据是先被读到了内存中,然后用数据写到文件中,当你数据读完的时候不代表你的数据已经写完了,因为还有一部分有可能会留在内存这个缓冲区中。这时候如果你调用了 Close()方法关闭了读写流,那么这部分数据就会丢失,所以应该在关闭读写流之前先Flush(),先清空数据。



示例一:FileInputStream类的使用    把文件读入到计算机内存中

public class FileDemo {
	public static void main(String[] args) {
		//创建一个文件对象  
		File file=new File("D:\\a.txt");
		
		FileInputStream in=null;
		try {
			in=new FileInputStream(file);
			byte[] buf=new byte[8*1024];
			int n=0;//读取的第几个字节  
			//从in中批量读取字节,放入buf字节数组中,从第0个位置开始放,最多放buf.length个,返回的是读到的字节的个数
			 while((n=in.read(buf,0,buf.length))!=-1){  
				//把字节数组中的内容转换成字符串  
                String s=new String(buf,0,n);  
                //输出字符串中的内容  
                System.out.println(s); 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try { //关闭文件流
				in.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}


打印:

hello 你好!


示例 二:FileOutputStream类的使用    从计算机内存输出到文件中

public class FileDemo {
	public static void main(String[] args) {
		File file=new File("D:\\b.txt");
		
		FileOutputStream out=null;
		if(!file.exists()){
			try {
				out = new FileOutputStream(file);
				String s1 = "hello 阳西一中!\r\n";
				String s2 = "hello 溪坎中学!";
				
				out.write(s1.getBytes());
				out.write(s2.getBytes());
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					out.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}else{
			 System.out.println("文件已经存在");  
		}
	}
}

示例三: 文件的拷贝( d:/a.txt向f:aa.txt拷贝)

public class FileDemo {
	public static void main(String[] args) {
		BufferedReader br=null;
		BufferedWriter bw=null;
		
		try {
			FileReader fr=new FileReader("d:/a.txt");
			br=new BufferedReader(fr);//不能简写(不能直接写"e:aa.txt") 
			
			//创建FileWriter对象  
            FileWriter fw=new FileWriter("f:/aa.txt");  
            bw=new BufferedWriter(fw);  
            //循环读取文件  
            String s="";  
            //包含该行内容的字符串,不包含任何终止符,如果已到达流末尾,则返回null  
            while((s=br.readLine())!=null){  
                bw.write(s+"\r\n");  
            }  
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				br.close();//后开先关闭  
                bw.close(); 
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}

示例四:

public class Student implements Serializable{
	private int age;
	private String name;

	public Student() {
	}

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

	public int getAge() {
		return age;
	}

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

	public String getName() {
		return name;
	}

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

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

}

public class FileDemo {
	public static void main(String[] args) throws Exception{
		String file="D:/d.txt";
		//1.对象的序列化
		/*ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
		Student stu = new Student(2, "张三");
		oos.writeObject(stu);
		oos.flush();
		oos.close();*/
		
		//1.对象的反序列化
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
		Student stu = (Student)ois.readObject();
		System.out.println(stu);
		ois.close();
	}
}

打印:

Student [age=2, name=张三]




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值