File类
File 类的基本概念
java.io.File类:文件和文件目录的抽象表示形式,与平台无关。- 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个
File对象,但是Java程序中的一个File对象,可以没有一个真实存在的文件或目录。 File能新建、删除、重命名文件和目录,但不能访问(读写)文件内容本身, 如果需要访问文件内容本身,则需要使用IO流。File对象可以作为参数传递给流的构造器。
File 类的构造器

三种基本构造器:
public File(String pathname):以pathname为路径创建File对象,可以是绝对路径或者相对路径。- 绝对路径:是一个固定的路径,从盘符开始
- 相对路径:是相对于某个位置开始,IDEA里是相对于当前工程或模块(main方法是相对于整个工程,单元测试里是相对当前模块)。
public File(String parent,String child):以parent为父路径,child为子路径创建File对象。public File(File parent,String child):根据一个父File对象和子文件路径创建File对象
关于分隔符:
- 路径中的每级目录之间用一个路径分隔符隔开,路径分隔符和系统有关:
- windows和DOS系统默认使用“
\”来表示 - UNIX和URL使用“
/”来表示
- windows和DOS系统默认使用“
- Java程序支持跨平台运行,因此路径分隔符要慎用,为了解决这个隐患,
File类提供了一个常量:public static final String separator。根据操作系统,动态的提供分隔符。
【示例代码】
@Testpublic void test1() {// 构造器1File file1 = new File("hello.txt");File file2 = new File("/Users/jyunkai/Documents/Code/JavaSE/IO/hi.txt");System.out.println(file1);//hello.txtSystem.out.println(file2);///Users/jyunkai/Documents/Code/JavaSE/IO/hi.txt// 构造器2File file3 = new File("/Users/jyunkai/Documents/Code", "JavaSE/IO");System.out.println(file3);///Users/jyunkai/Documents/Code/JavaSE/IO// 构造器3File file4 = new File(file3, "ha.txt");System.out.println(file4);///Users/jyunkai/Documents/Code/JavaSE/IO/ha.txt}
File类的常用方法
File类的获取功能
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数组。
【示例代码】
public class FileTest {@Testpublic void test1() {File file1 = new File("hello.txt");System.out.println(file1.getAbsoluteFile());System.out.println(file1.getPath());System.out.println(file1.getName());System.out.println(file1.getParent());System.out.println(file1.length());System.out.println(new Date(file1.lastModified()));File file = new File("/Users/eric/Documents/Code/Study/JavaBasic/FileAndIO");for (String s : Objects.requireNonNull(file.list())) {System.out.println(s);}for (File f : Objects.requireNonNull(file.listFiles())) {System.out.println(f);}}}
输出:
File类的重命名功能(剪切)
public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例:要想保证返回true,需要file1在硬盘中是存在的,且file2在硬盘中不存在。
示例代码:
@Testpublic void test5(){// hello.txt 在硬盘中是存在的File file1 = new File("hello.txt");// hi.txt 在硬盘中是不存在的File file2 = new File("/Users/jyunkai/Documents/IO/hi.txt");boolean renameTo = file1.renameTo(file2);System.out.println(renameTo);}
File类的判断功能
public boolean isDirectory():判断是否是文件目录public boolean isFile():判断是否是文件public boolean exists():判断是否存在public boolean canRead():判断是否可读public boolean canWrite():判断是否可写public boolean isHidden():判断是否隐藏
【示例代码】
@Testpublic void test3(){// File file1 = new File("hello.txt");File file1 = new File("/Users/jyunkai/Documents/Code/JavaSE");System.out.println(file1.isDirectory());System.out.println(file1.isFile());System.out.println(file1.canRead());System.out.println(file1.canWrite());System.out.println(file1.isHidden());}
File类的创建功能
public boolean createNewFile():创建文件,若文件存在则不创建,返回false。public boolean mkdir():创建文件目录,如果此文件目录存在就不创建了,如果此文件目录的上层目录不存在也不创建。public boolean mkdirs():创建文件目录,如果上层文件目录不存在,一并创建。
注意:如果你创建文件或者文件目录没有写盘符路径,那么默认在项目路径下(当前工程或模块)。
File类的删除功能
public boolean delete():删除文件或者文件夹。
【删除注意事项】
- Java中的删除不走回收站。
- 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录。
示例代码:
@Testpublic void test4() throws IOException {File file = new File("hi.txt");// 文件的创建与删除if (!file.exists()) {file.createNewFile();System.out.println("创建成功");} else {file.delete();System.out.println("删除成功");}// 文件目录的创建File file1 = new File("/Users/jyunkai/Documents/IO/io1");boolean mkdir = file1.mkdir();if (mkdir) {System.out.println("创建成功1");}File file2 = new File("/Users/jyunkai/Documents/IO/io2");boolean mkdirs = file2.mkdirs();if (mkdirs) {System.out.println("创建成功2");}//要想删除成功,文件目录下不能有子目录或文件System.out.println(file2.delete());}
IO流
IO基本概念
IO原理
- I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输,如读/写文件,网络通讯等。
- Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
IO流的分类
- 按操作数据单位不同分为:
- 字节流(8 bit):用于处理图片、视频等文件。
- 字符流(16 bit):用于处理文本文件。
- 按数据流的流向不同分为:
- 输入流:将硬盘中的文件中的数据读入到内存中。
- 输出流:将内存中的数据写出到硬盘中的文件里。
- 按流的角色的不同分为:
- 节点流(文件流):直接从数据源或目的地读写数据,主要是:
FileInputStreamFileOutputStreamFileReaderFileWriter
- 处理流:不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提 供更为强大的读写功能。
- 节点流(文件流):直接从数据源或目的地读写数据,主要是:


Java的IO流共涉及40多个类,实际上非常规则,都是从上图4个抽象基类派生的。由这四个类派生出来的子类名称都是以其父类名作为子类名后缀,如下图所示,其中背景颜色深的需要重点掌握。

节点流(文件流)
- 字符流操作字符,只能操作普通文本文件,最常见的文本文件有:.txt,.java,.c,.cpp 等。
FileReaderFileWriter
字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt,.xlsx等。
read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1。- 异常的处理:为了保证流资源一定可以执行关闭操作,需要使用
try-catch-finally处理。 - 读入的文件一定要存在,否则就会报
FileNotFoundException。
【示例代码】
@Testpublic void test1() {FileReader fr = null;try {//1.实例化File类的对象,指明要操作的文件File file = new File("hello.txt");//2.提供具体的流fr = new FileReader(file);//3.数据的读入//方式一:// int data = fr.read();// while (data != -1) {// System.out.print((char) data);// data = fr.read();// }//方式二:语法上针对于方式一的修改int data;while ((data = fr.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {//4.流的关闭if (fr != null) {try {fr.close();} catch (IOException e) {e.printStackTrace();}}}}//对read()操作升级:使用read的重载方法@Testpublic void test2() {FileReader fr = null;try {//1.File类的实例化File file = new File("hello.txt");//2.FileReader流的实例化fr = new FileReader(file);//3.读入的操作//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1char[] cbuf = new char[5];int len;while ((len = fr.read(cbuf)) != -1) {//方式一//错误的写法:// for (int i = 0; i < cbuf.length; i++) {// System.out.print(cbuf[i]);// }//正确的写法:// for (int i = 0; i < len; i++) {// System.out.print(cbuf[i]);// }//方式二//错误的写法:对应着方式一的错误写法// String s = new String(cbuf);//正确的写法:String s = new String(cbuf, 0, len);System.out.print(s);}} catch (IOException e) {e.printStackTrace();} finally {//4.资源的关闭if (fr != null) {try {fr.close();} catch (IOException e) {e.printStackTrace();}}}}
FileWriter
从内存中写出数据到硬盘的文件里。
说明:
- 输出操作对应的File可以不存在的,并不会报异常。
File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。File对应的硬盘中的文件如果存在:- 如果流使用的构造器是:
FileWriter(file,false)/FileWriter(file):对原有文件的覆盖; - 如果流使用的构造器是:
FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容。
- 如果流使用的构造器是:
【示例代码】
@Testpublic void test3() {FileWriter fw = null;try {//1.提供File类的对象,指明写出到的文件File file = new File("hi.txt");//2.提供FileWriter的对象,用于数据的写出fw = new FileWriter(file, true);//3.写出的操作fw.write("I have a dream.\n");fw.write("You need to have a dream.\n");} catch (IOException e) {e.printStackTrace();} finally {//4.流资源的关闭try {if (fw != null)fw.close();} catch (IOException e) {e.printStackTrace();}}}//读入和写出@Testpublic void test4() {FileReader fr = null;FileWriter fw = null;try {//1.创建File类的对象,指明读入和写出的文件File srcFile = new File("hello.txt");File destFile = new File("hi.txt");//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
使用字节流FileInputStream处理文本文件,可能出现乱码。下面的程序在控制台输出时候,中文会有乱码。
@Testpublic void test1() {File file = null;FileInputStream fis = null;try {//1.造文件file = new File("hello.txt");//2.造流fis = new FileInputStream(file);//3.读数据byte[] buffer = new byte[5];int len;while ((len = fis.read(buffer)) != -1) {String s = new String(buffer, 0, len);System.out.print(s);}} catch (Exception e) {e.printStackTrace();} finally {//4.关闭流资源if(fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
FileOutputStream
值得注意的是,复制操作可以操作文本文件,因为中间没有打印输出。
public void copyFile(String srcPath, String destPath) {FileInputStream fis = null;FileOutputStream fos = null;try {File srcFile = new File(srcPath);File destFile = new File(destPath);fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);byte[] buffer = new byte[1024];int len;while ((len = fis.read(buffer)) != -1) {fos.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void test2(){String srcPath = "爱情与友情.jpg";String destPath = "爱情与友情1.jpg";copyFile(srcPath, destPath);}
缓冲流(BufferedXxxxx)
为了提高数据的读写速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,使用8192个字节(8Kb)的缓冲区,如下所示:
【注意点】
- 缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
- 操作字节文件:
BufferedInputStream和BufferedOutputStream - 操作字符文件:
BufferedReader和BufferedWriter
- 操作字节文件:
- 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。
- 当使用
BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个字节(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。 - 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,
BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流。 - 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流。
flush()方法的使用:手动将buffer中内容写入文件,一般不需要手动。- 如果是带缓冲区的流对象的
close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。

【示例代码】
public class BufferedTest {//使用BufferedInputStream、BufferedOutputStream实现图片视频等文件的复制public void copyFileWithBuffered(String srcPath, String destPath) {BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//1.造文件File srcFile = new File(srcPath);File destFile = new File(destPath);//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[1024];int len;while ((len = bis.read(buffer)) != -1) {bos.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {//4.流的关闭//要求先关外层再关内存,在关闭外层的时候内层也会自动关闭if (bos != null) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void test1(){long start = System.currentTimeMillis();String srcPath = "/Users/jyunkai/Downloads/mac软件推荐1.mp4";String destPath = "/Users/jyunkai/Downloads/mac软件推荐1-1.mp4";copyFileWithBuffered(srcPath, destPath);long end = System.currentTimeMillis();System.out.println("花费时间:" + (end - start));//399-->118}//使用BufferedReader、BufferedWriter实现文本文件的复制@Testpublic void test2() {BufferedReader br = null;BufferedWriter bw = null;try {//创建文件和相应的流br = new BufferedReader(new FileReader(new File("红楼梦.txt")));bw = new BufferedWriter(new FileWriter(new File("红楼梦1.txt")));//读写操作//方式一:使用char[]// char[] cbuf = new char[1024];// int len;// while ((len = br.read(cbuf)) != -1) {// bw.write(cbuf, 0, len);// //bw.flush();// }//方式二:使用StringString data;while ((data = br.readLine()) != null) {bw.write(data);//data中不包含换行符bw.newLine();}} catch (IOException e) {e.printStackTrace();} finally {//关闭资源if (bw != null) {try {bw.close();} catch (IOException e) {e.printStackTrace();}}if (br != null) {try {br.close();} catch (IOException e) {e.printStackTrace();}}}}}
转换流
- 转换流提供了在字节流和字符流之间的转换,转换流属于字符流。
- Java API提供了两个转换流:
InputStreamReader:将InputStream转换为ReaderOutputStreamWriter:将Writer转换为OutputStream
- 字节流中的数据都是字符时,转成字符流操作更高效。
- 很多时候我们使用转换流来处理文件乱码问题,实现编码和解码的功能。



【示例代码】
public class IsReaderOsWriterTest {/*** 转换流的使用* 1.转换流:属于字符流* InputStreamReader:将一个字节的输入流转换为字符的输入流* OutputStreamWriter:将一个字符的输出流转换为字节的输出流** 2.作用:提供字节流与字符流之间的转换** 3. 解码:字节、字节数组 --->字符数组、字符串* 编码:字符数组、字符串 ---> 字节、字节数组** 4.字符集* ASCII:美国标准信息交换码,用一个字节的7位可以表示。* ISO8859-1:拉丁码表。欧洲码表,用一个字节的8位表示。* GB2312:中国的中文编码表,最多两个字节编码所有字符。* GBK:中国的中文编码表升级,融合了更多的中文文字符号,最多两个字节编码。* Unicode:国际标准码,融合了目前人类使用的所有字符,为每个字符分配唯一的字符码,所有的文字都用两个字节来表示。* UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。*/@Testpublic void test1(){InputStreamReader isr = null;OutputStreamWriter osw = null;try {//造文件、造流FileInputStream fis = new FileInputStream("红楼梦.txt");FileOutputStream fos = new FileOutputStream("红楼梦2.txt");isr = new InputStreamReader(fis);//使用系统默认的字符集,IDEA里设置的是UTF-8osw = new OutputStreamWriter(fos, "gbk");//指明字符集//读写过程char[] cbuf = new char[1024];int len;while ((len = isr.read(cbuf)) != -1) {osw.write(cbuf, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {//关闭资源try {if (osw != null)osw.close();} catch (IOException e) {e.printStackTrace();}try {if (isr != null)isr.close();} catch (IOException e) {e.printStackTrace();}}}}
标准输入输出流(System.in/out)
System.in和System.out分别代表了系统标准的输入和输出设备。- 默认输入设备是键盘,输出设备是显示器。
System.in的类型是InputStreamSystem.out的类型是PrintStream,其是OutputStream的子类,FilterOutputStream的子类- 重定向:通过
System类的setIn,setOut方法对默认设备进行改变。public static void setIn(InputStream in)public static void setOut(PrintStream out)
【练习】
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现。System.in —-> 转换流 —-> BufferedReader的readLine()
public class OtherStreamTest {public static void main(String[] args) {BufferedReader br = null;try {InputStreamReader isr = new InputStreamReader(System.in);br = new BufferedReader(isr);while (true) {System.out.print("请输入字符串:");String data = br.readLine();if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {System.out.println("程序结束");break;}String upperCase = data.toUpperCase();System.out.println(upperCase);}} catch (IOException e) {e.printStackTrace();} finally {if (br != null) {try {br.close();} catch (IOException e) {e.printStackTrace();}}}}}
打印流
打印流:PrintStream和PrintWriter,实现将基本数据类型的数据格式转化为字符串输出。
- 提供了一系列重载的
print()和println()方法,用于多种数据类型的输出。 PrintStream和PrintWriter的输出不会抛出IOException异常。PrintStream和PrintWriter有自动flush功能。PrintStream打印的所有字符都使用平台的默认字符编码转换为字节,在需要写入字符而不是写入字节的情况下,应该使用PrintWriter类。System.out返回的是PrintStream的实例。
【示例代码】
@Testpublic void test2() {PrintStream ps = null;try {//造文件、造流FileOutputStream fos = new FileOutputStream(new File("ASCII.txt"));//创建打印输出流,true为自动刷新模式(写入换行符或字节'\n'时都会刷新输出缓冲区)ps = new PrintStream(fos, true);if (ps != null) {//把标准输出流(控制台输出)改成文件System.setOut(ps);}//输出ASCII字符for (int i = 0; i <= 255; i++) {System.out.print((char) i);if (i % 50 == 0) {//每50个字符一行System.out.println();}}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (ps != null)ps.close();}}
数据流
为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
数据流有两个类,用于读取和写出基本数据类型、String类的数据,分别“套接”在 InputStream 和 OutputStream 子类的流上:
DataInputStreamDataOutputStream
DataInputStream 中的方法示例:
boolean readBoolean()char readChar()double readDouble()long readLong()String readUTF()byte readByte()float readFloat()short readShort()int readInt()void readFully(byte[] b)
DataOutputStream中的方法
- 将上述的方法的read改为相应的write即可。
【示例代码】
/*数据流DataInputStream 和 DataOutputStream作用:用于读取或写出基本数据类型的变量或字符串练习:将内存中的字符串、基本数据类型的变量写出到文件中。*/@Testpublic void test3() {DataOutputStream dos = null;try {dos = new DataOutputStream(new FileOutputStream("data.txt"));dos.writeUTF("杰克");dos.flush();//刷新操作,将内存中的数据写入文件dos.writeInt(18);dos.flush();dos.writeBoolean(true);dos.flush();} catch (IOException e) {e.printStackTrace();} finally {try {if (dos != null)dos.close();} catch (IOException e) {e.printStackTrace();}}}/*将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!*/@Testpublic void test4() {DataInputStream dis = null;try {dis = new DataInputStream(new FileInputStream("data.txt"));String name = dis.readUTF();int age = dis.readInt();boolean isMale = dis.readBoolean();System.out.println("name = " + name);System.out.println("age = " + age);System.out.println("isMale = " + isMale);} catch (IOException e) {e.printStackTrace();} finally {if (dis!=null) {try {dis.close();} catch (IOException e) {e.printStackTrace();}}}}
对象流
ObjectInputStream 和 OjbectOutputSteam 是用于存储和读取基本数据类型数据或对象的处理流。
- 它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
- 序列化:用
ObjectOutputStream类保存基本类型数据或对象的机制。 - 反序列化:用
ObjectInputStream类读取基本类型数据或对象的机制。
- 序列化:用
ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量。
关于对象的序列化
- 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。
- 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原。
- 序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是JavaEE 平台的基础。
- 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。 否则,会抛出
NotSerializableException异常。SerializableExternalizable
- 凡是实现
Serializable接口的类都有一个表示序列化版本标识符的静态变量:private static final long serialVersionUID;用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID可能发生变化,建议最好显式声明。- 简单来说,Java的序列化机制是通过在运行时判断类的
serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同 就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常InvalidCastException
- 简单来说,Java的序列化机制是通过在运行时判断类的
【示例代码】
public class ObjectInputOutputStreamTest {/*序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去使用ObjectOutputStream实现*/@Testpublic void test1() {ObjectOutputStream oos = null;try {oos = new ObjectOutputStream(new FileOutputStream("object.dat"));oos.writeObject(new String("我爱北京天安门"));oos.flush();oos.writeObject(new Person("jack", 24, new Account(2000)));oos.flush();} catch (IOException e) {e.printStackTrace();} finally {if (oos != null) {try {oos.close();} catch (IOException e) {e.printStackTrace();}}}}/*反序列化:将磁盘文件中的对象还原为内存中的一个java对象使用ObjectInputStream来实现*/@Testpublic void test2() {ObjectInputStream ois = null;try {ois = new ObjectInputStream(new FileInputStream("object.dat"));String str = (String) ois.readObject();Person person = (Person) ois.readObject();System.out.println(str);System.out.println(person);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if (ois!=null) {try {ois.close();} catch (IOException e) {e.printStackTrace();}}}}}
public class Person implements Serializable {/*** Person需要满足如下的要求,方可序列化* 1.需要实现接口:Serializable* 2.当前类提供一个全局常量:serialVersionUID* 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。* 默认情况下,基本数据类型都是可序列化的。* 补充:ObjectOutputStream 和 ObjectInputStream 不能序列化 static 和 transient 修饰的成员变量。*/private static final long serialVersionUID = 422983570235L;private String name;private int age;private Account account;public Person() {}public Person(String name, int age, Account account) {this.name = name;this.age = age;this.account = account;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Account getAccount() {return account;}public void setAccount(Account account) {this.account = account;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +", account=" + account +'}';}}
public class Account implements Serializable {private static final long serialVersionUID = 256998083235L;private double balance;public Account() {}public Account(double balance) {this.balance = balance;}public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}@Overridepublic String toString() {return "Account{" +"balance=" + balance +'}';}}
随机存取文件流
基本概念
RandomAccessFile声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。RandomAccessFile类支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读、写文件- 支持只访问文件的部分内容
- 可以向已存在的文件后追加内容
RandomAccessFile对象包含一个记录指针,用以标示当前读写处的位置:long getFilePointer():获取文件记录指针的当前位置。void seek(long pos):将文件记录指针定位到 pos 位置。
RandomAccessFile构造器public ``RandomAccessFile``(``File ``file, ``String ``mode)public ``RandomAccessFile``(``String ``name, ``String ``mode)- 创建
RandomAccessFile类实例需要指定一个mode参数,该参数指定RandomAccessFile的访问模式:r:以只读方式打开,不会创建文件而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。rw:打开以便读取和写入,如果文件不存在则会去创建文件,如果存在则不会创建。rwd:打开以便读取和写入,同步文件内容的更新。rws:打开以便读取和写入,同步文件内容和元数据的更新。
应用
我们可以用RandomAccessFile这个类,来实现一个多线程断点下载的功能, 用过下载工具的朋友们都知道,下载前都会建立两个临时文件,一个是与被下载文件大小相同的空文件,另一个是记录文件指针的位置文件,每次暂停的时候,都会保存上一次的指针,然后断点下载的时候,会继续从上 一次的地方下载,从而实现断点下载或上传的功能,有兴趣的朋友们可以 自己实现下。
【示例代码】
public class RandomAccessFileTest {@Testpublic void test1() {RandomAccessFile raf1 = null;RandomAccessFile raf2 = null;try {// r: 以只读方式打开;// rw:打开以便读取和写入;raf1 = new RandomAccessFile(new File("爱情与友情.jpg"), "r");raf2 = new RandomAccessFile(new File("爱情与友情2.jpg"), "rw");byte[] buffer = new byte[1024];int len;while ((len = raf1.read(buffer)) != -1) {raf2.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (raf1 != null) {try {raf1.close();} catch (IOException e) {e.printStackTrace();}}if (raf2 != null) {try {raf2.close();} catch (IOException e) {e.printStackTrace();}}}}/*使用RandomAccessFile实现数据的插入效果*/@Testpublic void test2() {RandomAccessFile raf = null;try {raf = new RandomAccessFile("hello.txt", "rw");// 将指针调到角标为3的位置raf.seek(3);// 保存指针3后面的所有数据到StringBuilder中StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());byte[] buffer = new byte[20];int len;while ((len = raf.read(buffer)) != -1) {builder.append(new String(buffer, 0, len));}// 调回指针,写入"xyz"raf.seek(3);raf.write("xyz".getBytes());// 将StringBuilder中的数据写入到文件中raf.write(builder.toString().getBytes());} catch (IOException e) {e.printStackTrace();} finally {if (raf != null) {try {raf.close();} catch (IOException e) {e.printStackTrace();}}}}}
拓展(详细的在框架时讲解)
NIO
Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的 IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的、基于通道的IO操作,而IO是面向流的。NIO将以更加高效的方式进行文件的读写操作。
Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。
java.nio.channels.ChannelFileChannel:处理本地文件SocketChannel:TCP网络编程的客户端的ChannelServerSocketChannel:TCP网络编程的服务器端的ChannelDatagramChannel:UDP网络编程中发送端和接收端的Channel
NIO.2
随着 JDK 7 的发布,Java对 NIO 进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 NIO.2。因为 NIO 提供的一些功能,NIO已经成为文件处理中越来越重要的部分。
Path/Paths/Files
- 早期的Java只提供了一个
File类来访问文件系统,但File类的功能比较有限,所提供的方法性能也不高。而且大多数方法在出错时仅返回失败,并不会提供异常信息。 - NIO. 2为了弥补这种不足,引入了
Path接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。 - Path可以看成是File类的升级版本,实际引用的资源也可以不存在。
在以前IO操作都是这样写的:
import java.io.File;File file = new File("index.html");
但在Java7 中,我们可以这样写:
import java.nio.file.Path;import java.nio.file.Paths;Path path = Paths.get("index.html");
- 同时,NIO.2在
java.nio.file包下还提供了Files、Paths工具类,Files包含了大量静态的工具方法来操作文件,Paths则包含了两个返回Path的静态工厂方法。 Paths类提供的静态get()方法用来获取Path对象:static Path get(String first, String ... more):用于将多个字符串串连成路径static Path get(URI uri):返回指定uri对应的Path路径



