10IO流
IO流
1 File类
1.1简介
- File类声明在java.io包下
- java.io.File:文件和文件目录路径的抽象表示形式,与平台无关
- File类的一个对象,代表一个文件或一个文件目录(俗称文件夹)
- File类中涉及到关于文件或文件目录的创建,删除,重命名,修改时间,文件大小等方法,并未涉及到写入或读取文件内容的操作,如果需要则必须使用IO流
- 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录
- File对象可以作为参数传递给流的构造器
1.2File类的使用:常用构造器
- public File(String pathname):以pathname为路径创建File对象,可以是绝对路径也可以是相对路径
- public File(String parent,String child):以parent为父路径,child为子路径创建File对象
- public File(File parent, String child):根据一个父File对象和子文件路径创建File对象
1.3File类的使用:路径
- 相对路径:相较于某个路径下,指明的路径
- 绝对路径:包含盘符在内的文件或文件目录的路径
- 说明:在idea中,如果大家开发使用Junit中的单元测试方法,相对路径即为当前Module下;如果大家使用main方法,相对路径即为当前Project下
- 在eclipse中,不管使用单元测试还是main相对路径都是当前的project下
- 路径分割符:windows \\ ; unix /
- 为了解决两者路径分隔符不同,File类提供一个常量:publiv static final String separator 根据操作系统,动态的提供分割符
- File file1=new File("d:\\fao\\hell.txt");
- File file1=new File("d:/fao/hell.txt");
- File file1=new File("d:"+File.separator+"fao"+File.separator+"hell.txt");
@Test
public void test1(){
//构造器1 public File(String pathname)
//相对于idea的module
File file1=new File("hello.txt");
File file2=new File("D:\\java\\faogaoji\\src\\bilifao28\\he.txt");
System.out.println(file1);//hello.txt
System.out.println(file2);//D:\java\faogaoji\src\bilifao28\he.txt
//构造器2 public File(String parent,String child)
File file3=new File("D:\\java\\faogaoji\\src","bilifao28");
System.out.println(file3);//D:\java\faogaoji\src\bilifao28
//构造器3 public File(File parent, String child)
File file4=new File(file3,"hi.txt");
System.out.println(file4);//D:\java\faogaoji\src\bilifao28\hi.txt
}
1.4 方法
常用方法
- public String getAbsolutePath():获取绝对路径
- public String getPath():获取路径
- public String getName():获取名称
- public String getParent():获取上层文件目录路径,若无,返回null
- public long length():获取文件长度(即字节数),不能获取目录的长度
- public long lastModified():获取最后一次的修改时间,毫秒值
用于文件夹的
- public String[] list():获取指定目录下的所有文件或者文件目录的名称数组
- public File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组
File类的重命名功能
- public boolean renameTo(File dest)把文件重命名为指定的文件路径
File类的判断功能
- public boolen isDirectory():判断是否是文件目录
- public boolen isFile():判断是否是文件
- public boolen exists():判断是否存在
- public boolen canRead():判断是否是可读
- public boolen canWrite():判断是否可写
- public boolen isHidden():判断是否隐藏
File类的创建删除功能
- public boolean createNewFile():创建文件,若文件存在则不创建,返回false
- public boolean mkdir():创建文件目录,如果此文件目录存在,就不创建;如果此文件目录上层目录不存在也不创建
- public boolean mkdirs():创建文件目录,如果上层文件目录不存在,一并创建;注意如果创建文件或者文件目录没有写盘符路径,那么默认在项目路径下
- public boolean delete():删除文件或者文件夹,注意java中删除不走回收站,要删除一个文件目录,请注意文件目录内不能包含文件或者文件目录
@Test
public void test2(){
File file1=new File("hello.txt");
File file2=new File("D:\\java\\faogaoji\\src\\bilifao28\\he.txt");
System.out.println(file1.getAbsolutePath());//D:\java\faogaoji\hello.txt
System.out.println(file1.getPath());//hello.txt
System.out.println(file1.getName());//hello.txt
System.out.println(file1.getParent());//null
System.out.println(file1.length());//7
System.out.println(file1.lastModified());//1627027882384
System.out.println();
System.out.println(file2.getAbsolutePath());
//D:\java\faogaoji\src\bilifao28\he.txt
System.out.println(file2.getPath());
//D:\java\faogaoji\src\bilifao28\he.txt
System.out.println(file2.getName());//he.txt
System.out.println(file2.getParent());
//D:\java\faogaoji\src\bilifao28
System.out.println(file2.length());//7
System.out.println(file2.lastModified());//1627027882384
}
@Test
public void test3(){
File file1=new File("D:\\java\\faogaoji\\src","bilifao28");
String[] list = file1.list();
for (String s:list){
System.out.println(s);
}
//G50File.java
//he.txt
System.out.println();
File[] files = file1.listFiles();
for (File f:files){
System.out.println(f);
}
//D:\java\faogaoji\src\bilifao28\G50File.java
//D:\java\faogaoji\src\bilifao28\he.txt
}
@Test
public void test4(){
File file1=new File("D:\\java\\faogaoji\\src\\bilifao28\\he2.txt");
File file2=new File("D:\\java\\faogaoji\\src\\bilifao27\\henew.txt");
boolean renameTo=file1.renameTo(file2);
System.out.println(renameTo);//true
}
@Test
public void test5(){
File file1=new File("hello.txt");
System.out.println(file1.isFile());//true
System.out.println(file1.isDirectory());//false
System.out.println(file1.exists());//true
System.out.println(file1.isHidden());//false
}
@Test
public void test6() throws IOException {
//文件创建,删除
File file1=new File("faotest.txt");
if (!file1.exists()){
file1.createNewFile();
System.out.println("创建成功");
}else {
file1.delete();
System.out.println("删除成功");
}
}
@Test
public void test7(){
//文件夹创建,删除
File file1=new File("D:\\java\\faogaoji\\faotest");
if (!file1.exists()){
file1.mkdir();
System.out.println("创建成功");
}else {
file1.delete();
System.out.println("删除成功");
}
}
2 IO流简介
2.1IO流原理
- I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输,如读/写文件,网络通讯等
- Java程序中,对于数据的输入/输出操作以"流stream"的方式进行
- java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据
- 输入input:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中
- 输出output:将程序(内存)数据输出到磁盘,光盘等存储设备

2.2 I/O流体分类及系结构
I/O流分类
- 按照操作数据单位:字节流,字符流
- 数据的流向:输入流,输出流
- 流的角色:节点流,处理流
I/O流体系结构
抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
InputStream FileInputStream BufferedInputStream
OutputStream FileOutputStream BufferedOutputStream
Reader FileReader BufferedReader
Writer FileWriter BufferedWriter

读入操作:read
- 实例化File类的对象,指明操作文件
- 提供具体的流
- 数据的读入
- 流的关闭操作
写出操作:write
- 实例化File类的对象,指明操作文件
- 提供具体的流
- 数据的写出
- 流的关闭操作
public class G51IOTest {
/*
将hello.txt文件读入程序中并输出到控制台
说明点:
1read()理解:返回读入的一个字符,如果达不到文件末尾返回-1
2异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
3读入的文件一定要存在,否则报FileNotFoundException异常
*/
@Test
public void test1() {
//try-catch快捷键ctrl+alt+t
FileReader fr= null;
try {
//1实例化File类的对象,指明操作文件
File file=new File("hello.txt");//相对路径,在test中是相对module
//main中可以是"faoIOhou\\hello.txt"
//2提供具体的流
fr = new FileReader(file);
//3数据的读入
//read()返回读入的一个字符,如果达到文件末尾,返回-1
//方式1
// int data = fr.read();
// while (data!=-1){
// System.out.print((char) data);
// data=fr.read();
// }
//方式2
int data;
while ((data=fr.read())!=-1){
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//4流的关闭操作
try {
if (fr!=null)//不加可能会报空指针异常
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
对read()操作升级:使用read的重载方法
*/
@Test
public void test2(){
FileReader fr= null;
try {
//1File类的实例化
File file=new File("hello.txt");
//2流的实例化
fr = new FileReader(file);
//3读入的操作
//read(char[] cbuf)返回每次读入cbuf数组中的字符个数
char[] cbuf=new char[6];
int len;
while((len=fr.read(cbuf))!=-1){
//for (int i=0;i<len;i++){
// System.out.print(cbuf[i]);
//}
//方式二
//错误的:因为最后一次可能不满这个长度 就会读到之前脏数据
//String str=new String(cbuf);
//System.out.println(cbuf);//hellowoldow
//正确的
String str=new String(cbuf,0,len);
System.out.print(str);//helloworld
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4资源的关闭
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
从内存中写出数据到硬盘的文件里
说明:
1输出操作,File可以不存在的
如果不存在,会自动创建文件
如果存在
如果使用FileWriter(file,false)或FileWriter(file)就是对原因文件覆盖
如果使用FileWriter(file,true)就是在原有文件上追加内容
*/
@Test
public void test3() throws IOException {
//注意下面省略了try-catch
//1提供File类对的对象
File file=new File("hello1.txt");
//2提供FileWriter的对象,用于数据的写出
//true就是追加 false或者默认就是覆盖
FileWriter fw=new FileWriter(file,true);
//3写出操作
fw.write("i have a dream\n");
fw.write("you need to have a dream");
//4流资源的关闭
fw.close();
}
/*
对write()操作升级:使用read的重载方法,重点掌握下面这个例子!!!
*/
@Test
public void test4() {
FileReader fr= null;
FileWriter fw= null;
try {
//1创建File类对象,指明读入和写出的文件
File srcFile=new File("hello.txt");
File destFile=new File("hello2.txt",true);//此处表示追加到后面
//2创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
//3数据的读入和写出操作
char[] cbuf=new char[5];
int len;//记录每次读入到数组中的长度
while ((len=fr.read(cbuf))!=-1){
//每次写出len个字符
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4流关闭
try {
if (fw!=null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字节流(FileInputStream和FileOutpuStream)和字符流(FileReader和FileWriter)区别
- 对于文本文件(.txt .java .c .cpp),使用字符流处理
- 对于非文本文件(.jpg .mp3 .doc .ppt .avi),使用字节流处理
- 但是对于文本复制操作,字节流处理也可以,因为直接原封不动复制过去,当中不看
public class G52FileLiu {
//使用字节流处理文本文件可能出现乱码
@Test
public void test1() throws IOException {
//1造文件
File file=new File("hello3.txt");
//2造流
FileInputStream fis=new FileInputStream(file);
//3读数据
byte[] buffer=new byte[5];
int len;
while ((len=fis.read(buffer))!=-1){
String str=new String(buffer,0,len);
System.out.print(str);//helloabcd123中国��
}
//4关闭流
fis.close();
}
//使用字节流处理非文本文件
//实现对图片的复制操作
@Test
public void test2() {
FileInputStream fis= null;
FileOutputStream fos= null;
try {
//1造文件
File file1=new File("test1.jpg");
File file2=new File("test2.jpg");
//2造流
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
//3读数据
byte[] buffer=new byte[5];
int len;
while ((len=fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4关闭流
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//指定路径下文件的复制
public void copyFile(String srcPath,String destPath){
FileInputStream fis= null;
FileOutputStream fos= null;
try {
//1造文件
File file1=new File(srcPath);
File file2=new File(destPath);
//2造流
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
//3读数据
byte[] buffer=new byte[1024];//会影响时间 通常1024
int len;
while ((len=fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4关闭流
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test3(){
long start=System.currentTimeMillis();
String srcPath="test1.jpg";
String destPath="test3.jpg";
copyFile(srcPath,destPath);
long end=System.currentTimeMillis();//时间从64变成1
System.out.println("复制操作时间为:"+(end-start));
}
}
4 处理流之一:缓冲流的使用
- 处理流:就是套接在已有的流的基础上
- 缓冲流:BufferedInputStream;BufferedOutputStream;BufferedReader;BufferedWriter
- 作用:提高流的读取,写入速度
- 原因:内部提供了缓冲区
public class G53HuanChongLiu {
//实现非文本文件的复制
@Test
public void test1() {
BufferedInputStream bis= null;
BufferedOutputStream bos= null;
try {
//1造文件
File srcFile=new File("test1.jpg");
File destFile=new File("test4.jpg");
//2造流
//2.1先造节点流
FileInputStream fis=new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3复制的细节,读取和写入
byte[] buffer=new byte[5];
int len;
while ((len=bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4资源关闭
//要求先关外层流,再关内层流
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
//说明:在关闭外层时会自动关闭内存,所以内存可以省略 写上也不错
//fos.close();
//fis.close();
}
}
//实现文件复制的方法
public void copyBuffer(String srcPath,String destPath){
FileInputStream fis= null;
FileOutputStream fos= null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
//1造文件
File file1=new File(srcPath);
File file2=new File(destPath);
//2造流
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
bis=new BufferedInputStream(fis);
bos=new BufferedOutputStream(fos);
//3读数据
byte[] buffer=new byte[5];
int len;
while ((len=bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4关闭流
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test2(){
long start=System.currentTimeMillis();
String srcPath="test1.jpg";
String destPath="test5.jpg";
copyBuffer(srcPath,destPath);
long end=System.currentTimeMillis();//原来64现在18
System.out.println("复制操作时间为:"+(end-start));
}
}
4 处理流之二:转换流的使用
- InputStreamReader:将一个字节的输入流(InputStream)转换为字符的输入流(Reader)
- OutputStreamWriter:将一个字符的输出流(Writer)转换为字节的输出流(OutputStream)
- 作用:提供字节流和字符流之间的转换
- 很多时候我们使用转换流来处理文件乱码问题,实现编码和解码的功能
- 解码:InputStreamReader; 编码:OutputStreamWriter
public class G54ZhuanHuanLiu {
//InputStreamReader:实现字节的输入流转换为字符的输入流
@Test
public void test1() throws IOException {
File file=new File("huan1.txt");
FileInputStream fis=new FileInputStream(file);
InputStreamReader isr=new InputStreamReader(fis);
//使用系统默认的字符集合 可以加,“UTF-8”
//参数二指明了字符集,具体使用哪个根据当初保存的时候的字符集
char[] cbuf=new char[2];
int len;
while ((len=isr.read(cbuf))!=-1){
String str=new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
}
//综合使用--处理乱码问题
@Test
public void test2() throws IOException {
File file1=new File("huan1.txt");
File file2=new File("huan2.txt");
FileInputStream fis=new FileInputStream(file1);
FileOutputStream fos=new FileOutputStream(file2);
InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
OutputStreamWriter osw=new OutputStreamWriter(fos,"gbk");
char[] cbuf=new char[5];
int len;
while ((len=isr.read(cbuf))!=-1){
osw.write(cbuf,0,len);
}
isr.close();
osw.close();
}
}
5 处理流之三四无:标准的输入输出流;打印流;数据流
5.1 标准的输入输出流
- System.in:标准的输入流,默认从键盘输入
- System.out:标准的输出流,默认从控制台输出
- System类的setIn()/setOut()方式重新指定输入和输出流
- 例题:从键盘输入字符串,要求将读到的字符串转成大写输出,然后继续进行输入操作,直到输入"e"或者"exit"时,退出程序
public static void main(String[] args) throws IOException {
InputStream si=System.in;//标准输入流
InputStreamReader isr = new InputStreamReader(si);//转换流
BufferedReader br=new BufferedReader(isr);//缓冲流
while (true){
System.out.println("输入");
String data= br.readLine();
if (data.equals("e")||data.equals("exit")){
System.out.println("程序结束");
break;
}
String upperCase=data.toUpperCase();
System.out.println(upperCase);
}
br.close();
}
5.2 打印流
-
实现将基本数据类型的数据格式转换为字符串输出
-
打印流:PrintStream和PrintWriter
-
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
-
PrintStream和PrintWriter的输出不会抛出IOException异常
-
PrintStream打印的所有字符都使用平台的默认字符编码转换为字节;
-
在需要写入字符而不是字节的情况下应该使用PrintWriter
-
System.out返回的是PringStream的实例
@Test public void testDaYing() throws Exception{ FileOutputStream fos = new FileOutputStream(new File("daying.txt")); //创建打印输出流,设置为自动刷新模式(写入换行符或\n是都会刷新输出缓冲区) PrintStream ps = new PrintStream(fos, true); if (ps!=null){//把标准输出流(控制台)改成文件 System.setOut(ps); } for (int i=1;i<=100;i++){//输出1-100 System.out.print(i); if (i % 20==0){//每隔20个换行 System.out.println(); } } ps.close(); }
5.3 数据流
- 为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流
- 作用:用于读取或写出基本数据类型的变量或字符串
- 注意点:读取数据的顺序要和写入数据的顺序一致
- 数据流:DataInputStream和DataOutputStream分别套接在InputStream和OutputStream子类的流上
- DataInputStream常用方法:readBoolean(); readByte(); readChar(); readFloat(); readDouble(); readShort(); readLong(); readInt(); readUTF(); reaFully(byte[] b);
- DataOutputStream常用方法:将上面read改成write
@Test
public void test3() throws IOException {
DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("fao");
dos.writeInt(13);
dos.writeBoolean(true);
dos.close();
}
@Test
public void test4() throws IOException {
DataInputStream dis=new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println(name+" "+age+" "+isMale);
}
}
6 处理流之六:对象流
简介:
- ObjectInputStream和ObjectOutputStream
- 用于存储和读取基本数据类型数据或对象的处理流。
- 它的强大之处就是可以把java值的对象写入到数据源中,也能把对象从数据源中还原回来
- 序列化:使用ObjectOutputStream将内存中java对象保存到磁盘中或通过网络传输出去
- 反序列化:使用ObjectInputStream将磁盘文件中的对象还原为内存中的一个java对象
- 不能序列化static和transient修辞的成员 但是不会报错 会出现null
public class G56DyuXiangLiu {
/*
序列化过程:将内存中java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream
*/
@Test
public void test1() {
ObjectOutputStream oos= null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
oos.writeObject(new String("我爱上海"));
oos.flush();//刷新操作
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos!=null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
反序列化:将磁盘文件中的对象还原为内存中的一个java对象
使用ObjectInputStream
*/
@Test
public void test2(){
ObjectInputStream ois= null;
try {
ois = new ObjectInputStream(new FileInputStream("object.txt"));
Object obj = ois.readObject();
String str=(String) obj;
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
序列化详解
- 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其他程序获取了这种二进制流,就可以恢复成原来的Java对象。
- 序列化的好处在于看将任何实现了Sericable接口的对象转化为字节数据,使其在保存和传输时可被还原
- 序列化是RMI(远程方法调用)过程的参数和返回值都必须实现的机制,而RMI是JavaEE的基础,因此序列化机制是JavaEE平台的基础
- 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一(Serializable,Externalizable),否则会抛出NotSerializableException异常
- 凡是实现Serializable接口的类都有一个表示序列化版本标识的静态变量:private staitc final long serialVersionUID
- serialVersionUID用来表明类的不同版本的兼容性,简言之,其目的是以序列化对象进行版本控制,有关各版本发序列化时是否兼容
- 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的,若类的实例变量做了修改,serialVersionUID可能发生变化,所以建议显示声明
- 简单来说。Java的序列化机制是通过在运行时判断类的 serialVersionUID来验证版本一致性,在进行反序列化是,JVM会把传来的字节流中的 serialVersionUID与本地相应实体类的 serialVersionUID进行比较,如果相同则认为是一致的,可以进行反序列化,否则就会出现反序列版本不一致的异常(InvalidCastException)
序列化步骤:Person需要满足如下要求
- 需要实现接口Serializable
- 需要当前类提供一个全局常量 public static final long serialVersionUID
- 除了当前Person类需要实现Serializable接口以外,要保证内部所有属性也是可序列化的,默认情况下基本数据类型也是可序列化的
- 不能序列化static和transient修辞的成员
public class G57ZiDingYiDuiXiangLei {
@Test
public void test1(){
ObjectOutputStream oos= null;
try {
oos = new ObjectOutputStream(new FileOutputStream("Zobject.txt"));
oos.writeObject(new Person(123,"fao"));
oos.flush();//刷新操作
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos!=null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test2(){
ObjectInputStream ois= null;
try {
ois = new ObjectInputStream(new FileInputStream("Zobject.txt"));
Object obj = ois.readObject();
Person p=(Person) obj;
System.out.println(p.toString());
//Person{age=123, name='fao'}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//需要实现接口Serializable
class Person implements Serializable {
//需要当前类提供一个全局常量 public static final long serialVersionUID
public static final long serialVersionUID=475463532L;
private int age;
private String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public Person() {
}
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;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
7 RandomAccessFile
简介
- RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。
- RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意
地方来读、写文件:支持只访问文件的部分内容;可以向已存在的文件后追加内容 - RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。
- RandomAccessFile 类对象可以自由移动记录指针:
- long getFilePointer():获取文件记录指针的当前位置
- void seek(long pos):将文件记录指针定位到 pos 位置
构造器
- public RandomAccessFile(File file, String mode)
- public RandomAccessFile(String name, String mode)
- 创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
- r: 以只读方式打开
- rw:打开以便读取和写入
- rwd:打开以便读取和写入;同步文件内容的更新
- rws:打开以便读取和写入;同步文件内容和元数据的更新
- 如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件, 如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。
public class G58RandomDuiXiangLiu {
@Test
public void test1() throws IOException {
RandomAccessFile raf1=new RandomAccessFile("random1.txt","r");
RandomAccessFile raf2=new RandomAccessFile("random2.txt","rw");
byte[] buffer=new byte[1024];
int len;
while ((len=raf1.read(buffer))!=-1){
raf2.write(buffer,0,len);
}
raf1.close();
raf2.close();
}
@Test
public void test2() throws IOException{
RandomAccessFile raf1=new RandomAccessFile("random3.txt","rw");
raf1.seek(3);//将文件记录指针定位到3
raf1.write("xyz".getBytes(StandardCharsets.UTF_8));
raf1.close();
//random3.txt从abcdeghijk变成abcxyzghijk
}
/*
实现插入效果
*/
@Test
public void test3() throws IOException{
RandomAccessFile raf1=new RandomAccessFile("random3.txt","rw");
raf1.seek(3);
//可变字符序列 因为length返回Long 所以强转成int
StringBuilder builder=new StringBuilder((int)new File("random3.txt").length());
byte[] buffer=new byte[20];
int len;
while ((len=raf1.read(buffer))!=-1){
//保存指针后面所有数据
builder.append(new String(buffer,0,len));
}
//调回指针,写
raf1.seek(3);
raf1.write("fao".getBytes(StandardCharsets.UTF_8));
//将StringBuilder中的数据写入到文件中
raf1.write(builder.toString().getBytes(StandardCharsets.UTF_8));
raf1.close();
}
}

浙公网安备 33010602011771号