java中处理文件的对象 : File
我们通过构造参数获取到file的对象,可以通过这个对象在内存层面创造文件或者文件夹
流的分类:
1.按照数据单位:字节流丶字符流
2.按照数据的流向:输入流丶输出流
3.流的角色:节点流丶处理流
流的基类: InputStream OutputStream Reader Writer
进行写入写出的套路:
1.获取文件的对象 new File()
2.获取写入,写出流的对象 new InputStream() , new OutputStream()
3.进行写入丶写入的操作 read()方法 write()方法
4.关闭流
注意:使用try catch finally 方式 ,将关闭流操作放入finally中去
当文件中有汉字的时候,最好不要以byte字节的方式进行传输,应该创建char字符数组,当在内存层面去读的时候,可能会造成乱码
当文件是音乐,图片类型的时候,不能以char字符的方式进行传输,应该创建byte字节数组
图片复制的方法
//图片,音频类型的文件复制方法
public void copyFile(String Start,String end){
File file = new File(Start);
File file1 = new File(end);
FileInputStream fileInputStream= null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(file1);
byte[] arr = new byte[1024];
int len;
while ((len = fileInputStream.read(arr))!=-1){
fileOutputStream.write(arr,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
文本文件复制
public static void main(String[] args) {
//文件复制
FileWriter fileOut = null;
FileReader FileIn = null;
try {
File file = new File("hello1.txt");
File file1 = new File("hello2.txt");
FileIn = new FileReader(file);
fileOut= new FileWriter(file1);
char[] arr = new char[5];
int len;
while ((len=FileIn.read(arr))!=-1){
fileOut.write(arr,0,len);
// for (int i = 0; i < len; i++) {
// fileOut.write(arr[i]);
//
//
// }
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(FileIn!=null)
FileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileOut!=null)
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在实践应用中,我们一般进行复制操作会使用缓冲流,使用缓冲流的时候需要将节点流包裹起来
在关闭流的时候,只需要关闭缓冲流就行,节点流会自动关闭
应用:
package omg;
import java.io.*;
/**
* Created with IntelliJ IDEA.
*
* @Author: DIXian
* @Date: 2021/06/26/22:23
*/
public class Test13 {
public static void main(String[] args) {
//文本文件的复制
BufferedReader bu = null;
BufferedWriter buf = null;
try {
bu = new BufferedReader(new FileReader(new File("hello1.txt")));
buf= new BufferedWriter(new FileWriter(new File("hello3.txt")));
//将文本读入char数组中,创建
char[] arr = new char[1024];
//记录读取到的长度
int len;
while ((len = bu.read(arr)) != -1){
buf.write(arr,0,len);
System.out.println("复制成功");
}
bu.close();
buf.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bu.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
关于转换流:可以用来讲字节流转换为字符流,将字符流转换为字节流,使用方法和缓冲流相似
InputstreamReader:将字节输入流转换为字符输入流
OutputStreamWriter:将字符输出流转换为字节输出流
序列化和反序列化 :其中使用的是对象流
即将对象以字节的方式写出到硬盘文件中为序列化:
ObjectOutputStream
将对象从磁盘文件中以字节方式读取出来为反序列化
ObjectInputStream
如果需要将自定义对象实现序列化和反序列化,需要两步:
1.实现序列化接口
2.在自定义对象中设置自定义版本序列号
3.保证自定义对象的所有属性都是可序列化的
如果不想序列化对象的某个属性,可使用static 或者transient修饰