JavaSE 基础笔记之IO
File类
java.io.File类
1)凡是与输入、输出相关的类、接口等都定义在java.io包下
2)File是一个类,可以有构造器创建其对象。此对象对应着一个文件(.txt .avi .doc .ppt .mp3 .jpg)或文件目录
3)File类对象与平台无关的
4)File中的方法,仅涉及到如何创建、删除、重命名等等。只要涉及文件内容的,File是无能为力的,必须由io流来完成
5)File类的对象常作为io流的具体类的构造器的形参
File类常用方法
/* * File类常用方法总结: * getName():获取文件或文件夹名称 * getPath():返回定义时的路径(就是你写的什么路径,他返回什么路径) * getAbsolutePath():获取文件的绝对路径,与文件是否存在没关系,返回的是一个字符串,这个字符串就是当前File对象的绝对路径名的字符串形式 * getParent():返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null。 * getAbsoluteFile():返回的是一个File类对象,这个File类对象表示是当前File对象的绝对路径名形式 * renameTo():如果目标文件与源文件在同一路径下,那么renameTo的作用是重命名 * 如果目标文件与源文件不在同一路径下,那么renameTo的作用是剪切,而且不能操作文件夹 * 文件名不区分大小写,文件夹名区分大小写. * exists():判断文件或文件夹是否存在,存在返回true * canWrite():判断文件或文件夹是否可写,可写返回true * canRead():判断文件或文件夹是否可读,可读返回true * isFile():判断是否是一个文件,如果不存在,则始终为false * isDirectory():判断是否为一个目录,如果不存在,则始终为false * lastModified():获取最后一次被修改的时间,世家你是从1970年午夜至最后一次修改时间的毫秒数 * length():获取文件的大小(字节数),如果文件不存在或为一个文件夹,返回0 * createNewFile():在指定位置创建一个空文件,成功返回true,如果已存在就不创建,返回false * delete():删除文件或者一个空文件夹,不能删除非空文件夹,返回一个布尔值 * mkDir():创建一个文件目录,只有在上层文件目录存在的情况下,才能返回true/在指定位置创建一个单级文件夹 * mkDirs():创建一个文件目录,若上层文件目录不存在,一并创建/在指定位置创建一个多级文件夹 * list():返回目录下的文件或目录名(String[]),包含隐藏文件,对于文件操作会返回null * listFiles():返回目录下的文件或者目录对象(File类实例,File[]),包含隐藏文件,对于文件操作会返回null */
1 /* 2 * 路径:绝对路径 & 相对路径 3 * 绝对路径:包括盘符在内的完成的文件路径 4 * 相对路径:在当前文件目录下的文件的路径 5 */
1)访问文件名
1 public void test() { 2 File file1 = new File("e:\\io\\helloworld.txt");//绝对路径,对应文件 3 File file2 = new File("hello1.txt");//相对路径 4 File file3 = new File("e:/io/IO2");//对应文件夹 5 File file4 = new File("HELLO.txt"); 6 File file5 = new File("e:\\io\\io2"); 7 8 System.out.println(file1.getName()); 9 //获取文件或文件夹名称 10 System.out.println(file1.getPath()); 11 //返回定义时的路径(就是你写的什么路径,他返回什么路径) 12 System.out.println(file1.getAbsolutePath()); 13 //获取文件的绝对路径,与文件是否存在没关系,返回的是一个字符串,这个字符串就是当前 14 //File对象的绝对路径名的字符串形式 15 System.out.println(file1.getParent()); 16 //返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null。 17 System.out.println(file1.getAbsoluteFile()); 18 //返回的是一个File类对象,这个File类对象表示是当前File对象的绝对路径名形式 19 20 System.out.println(); 21 System.out.println(file2.getName()); 22 System.out.println(file2.getPath()); 23 System.out.println(file2.getAbsolutePath()); 24 System.out.println(file2.getParent()); 25 System.out.println(file2.getAbsoluteFile()); 26 27 //renameTo(File newName):重命名 28 //file1.renameTo(file2):file1重命名为file2 29 //要求:file1文件一定存在,file2一定不存在 30 boolean b = file1.renameTo(file2); 31 System.out.println(b); 32 /* 33 * 注意:文件名不区分大小写,文件夹名区分大小写。 34 * 如果目标文件与源文件在同一路径下,那么renameTo的作用是重命名 35 * 如果目标文件与源文件不在同一路径下,那么renameTo的作用是剪切,而且不能操作文件夹 36 */ 37 boolean b1 = file5.renameTo(file3); 38 System.out.println(b1); 39 }
输出结果:
helloworld.txt
e:\io\helloworld.txt
e:\io\helloworld.txt
e:\io
e:\io\helloworld.txt
hello1.txt
hello1.txt
D:\eclipse_workspace\JavaSE_IO\hello1.txt
null
D:\eclipse_workspace\JavaSE_IO\hello1.txt
2)文件检测
1 public void test1() { 2 File file1 = new File("e:\\io\\helloworld.txt"); 3 File file2 = new File("e:/io/IO2"); 4 5 System.out.println(file1.exists()); 6 //判断文件或文件夹是否存在,存在返回true 7 System.out.println(file1.canWrite()); 8 //判断文件或文件夹是否可写,可写返回true 9 System.out.println(file1.canRead()); 10 //判断文件或文件夹是否可读,可读返回true 11 System.out.println(file1.isFile()); 12 //判断是否是一个文件,如果不存在,则始终为false 13 System.out.println(file1.isDirectory()); 14 //判断是否为一个目录,如果不存在,则始终为false 15 System.out.println(file1.lastModified()); 16 //获取最后一次被修改的时间,世家你是从1970年午夜至最后一次修改时间的毫秒数 17 System.out.println(file1.length()); 18 //获取文件的大小(字节数),如果文件不存在或为一个文件夹,返回0 19 20 System.out.println(); 21 System.out.println(file2.exists()); 22 System.out.println(file2.canWrite()); 23 System.out.println(file2.canRead()); 24 System.out.println(file2.isFile()); 25 System.out.println(file2.isDirectory()); 26 System.out.println(file2.lastModified()); 27 System.out.println(file2.length()); 28 29 /* 输出结果: 30 * true 31 true 32 true 33 true 34 false 35 1523527334225 36 10 37 38 true 39 true 40 true 41 false 42 true 43 1523524277487 44 0 45 */ 46 }
1 public void test2() throws IOException { 2 File file1 = new File("e:\\io\\helloworld.txt"); 3 4 System.out.println(file1.delete()); 5 //删除文件或者一个空文件夹,不能删除非空文件夹,返回一个布尔值 6 if(!file1.exists()){ 7 boolean b = file1.createNewFile(); 8 //在指定位置创建一个空文件,成功返回true,如果已存在就不创建,返回false 9 System.out.println(b); 10 } 11 12 File file2 = new File("e:/io"); 13 if(!file2.exists()){ 14 boolean b1 = file2.mkdir(); 15 //创建一个文件目录,只有在上层文件目录存在的情况下,才能返回true 16 //在指定位置创建一个单级文件夹 17 System.out.println(b1); 18 } 19 File file3 = new File("e:/io1/io1"); 20 if(!file3.exists()){ 21 boolean b1 = file3.mkdirs(); 22 //创建一个文件目录,若上层文件目录不存在,一并创建 23 //在指定位置创建一个多级文件夹 24 System.out.println(b1); 25 } 26 String[] str = file2.list(); 27 //返回目录下的文件或目录名(String[]),包含隐藏文件,对于文件操作会返回null 28 for(int i = 0; i < str.length; i++){ 29 System.out.println(str[i]); 30 } 31 File[] files = file2.listFiles(); 32 //返回目录下的文件或者目录对象(File类实例,File[]),包含隐藏文件,对于文件操作会返回null 33 for(int i = 0; i < files.length; i++){ 34 System.out.println(files[i].getName()); 35 } 36 /* 输出结果: 37 * true 38 * true 39 * true 40 * true 41 * helloworld.txt 42 io1 43 IO2 44 helloworld.txt 45 io1 46 IO2 47 */ 48 }
IO流
IO流用来处理设备之间的数据传输
Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据
输入input:读取外部数据(磁盘,光盘等存储设备中的数据)到程序(内存)中
输出output:将程序(内存)数据输出到磁盘,光盘等存储设备中
流的分类
按操作数据单位不同分为:字节流(8bit),字符流(16bit)
按数据流的流向不同分为:输入流,输出流
按流的角色不同分为:节点流,处理流
FileInputStream和FileOutputStream
package com.robin.java; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.junit.Test; /* * 1.流的分类 * 按照数据流向不同:输入流 输出流 * 按照处理数据的单位不同:字节流 字符流(处理的文本文件) * 按照角色的不同:节点流(直接作用于文件的) 处理流 * 2.IO流的体系 * 抽象基类 节点流(文件流) 缓冲流(处理流的一种) * InputStream FileInputStream BufferedInputStream * OutputStream FileOutputStream BufferedOutputStream * Reader FileReader BufferedReader * Writer FileWriter BufferedWriter */ public class TestInputOutputStream { //从硬盘存在的一个文件中,读取其内容到程序中,使用FileInputStream //要读取的文件一定要存在,否则抛FileNotFoundException @Test public void testFileInputStream1() throws IOException{ //1.创建一个File类的对象。 File file = new File("hello.txt"); //2.创建一个FileInputStream类的对象 FileInputStream fis = new FileInputStream(file); //3.调用FileInputStream的方法,实现file文件的读取。 /* * read():读取文件的一个字节。当执行到文件结尾时,返回-1 */ int b = fis.read(); while(b != -1){ System.out.print((char)b); b = fis.read(); } //4.关闭相应的流 fis.close(); } //使用try-catch的方式处理如下的异常更合理:保证流的关闭操作一定可以执行 @Test public void testFileInputStream2(){ //2.创建一个FileInputStream类的对象 FileInputStream fis = null; try { //1.创建一个File类的对象。 File file = new File("hello.txt"); fis = new FileInputStream(file); //3.调用FileInputStream的方法,实现file文件的读取。 /* * read():读取文件的一个字节。当执行到文件结尾时,返回-1 */ int b = fis.read(); while(b != -1){ System.out.print((char)b); b = fis.read(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //4.关闭相应的流 if(fis != null){ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //利用字节数组去读文件 @Test public void testFileInputStream3(){ FileInputStream fis = null; try { File file = new File("hello.txt"); fis = new FileInputStream(file); byte[] b = new byte[7];//读取到的数据要写入的数组 int len;//每次读入到byte数组中的字节的长度 while((len = fis.read(b)) != -1){ //方式一 /* for(int i = 0; i < len; i++){ System.out.print((char)b[i]); } */ //方式二 String str = new String(b, 0, len); System.out.print(str); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fis != null){ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //FileOutputStream @Test public void testFileOutputStream1(){ //1.创建一个File对象,表明要写入的文件位置 //输出的物理文件可以不存在,当执行过程中,若不存在,会自动的创建。若存在,会将原有的文件覆盖 File file = new File("hello1.txt"); //2.创建一个FileOutputStream的对象,将file对象作为形参传递给FileOutputStream构造器中 FileOutputStream fos = null; try{ fos = new FileOutputStream(file); //3.写入的操作 fos.write(new String("I love China").getBytes()); }catch(Exception e){ e.printStackTrace(); }finally{ //4.关闭输出流 if(fos != null){ try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //从硬盘读取一个文件,并写入到另一个位置。(相当于文件的复制) @Test public void testFileInputOutputStream(){ //1.提供读入、写出的文件 File file1 = new File("C:/Users/Robin/Desktop/1.png"); File file2 = new File("2.png"); //2.提供相应的流的对象 FileInputStream fis = null; FileOutputStream fos = null; try{ fis = new FileInputStream(file1); fos = new FileOutputStream(file2); //3.实现文件的复制 byte[] b = new byte[20]; int len; while((len = fis.read(b)) != -1){ fos.write(b, 0, len); //fos.write(b);错误的写法 等同于fos.write(b,0,b.length); } }catch(Exception e){ e.printStackTrace(); }finally{ if(fos != null){ try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //实现文件复制的方法 public void copyFile(String src,String dest){ //1.提供读入、写出的文件 File file1 = new File(src); File file2 = new File(dest); //2.提供相应的流的对象 FileInputStream fis = null; FileOutputStream fos = null; try{ fis = new FileInputStream(file1); fos = new FileOutputStream(file2); //3.实现文件的复制 byte[] b = new byte[20]; int len; while((len = fis.read(b)) != -1){ fos.write(b, 0, len); //fos.write(b);错误的写法 等同于fos.write(b,0,b.length); } }catch(Exception e){ e.printStackTrace(); }finally{ if(fos != null){ try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void testCopyFile(){ long start = System.currentTimeMillis(); String src = "C:/Users/Robin/Desktop/1.wmv"; String dest = "C:/Users/Robin/Desktop/2.wmv"; copyFile(src, dest); long end = System.currentTimeMillis(); System.out.println("花费的时间为: " + (end - start)); //8348 } }
FileReader和FileWriter
package com.robin.java; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.junit.Test; /* * 使用FileReader FileWriter 可以实现文本文件的复制。 * 对于非文本文件(视频文件、音频文件、图片)只能使用字节流 */ public class TestFileReaderWriter { @Test public void testFileReaderWriter(){ //1.输入流对应的文件src一定要存在,否则抛异常。输出流对应的文件dest可以不存在,执行过程中会自动创建 FileReader fr = null; FileWriter fw = null; try{ File src = new File("dbcp.txt"); File dest = new File("dbcp1.txt"); //2. fr = new FileReader(src); fw = new FileWriter(dest); //3. char[] c = new char[24]; int len; while((len = fr.read(c)) != -1){ fw.write(c, 0, len); } }catch(Exception e){ e.printStackTrace(); }finally{ //4. if(fw != null){ try { fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fr != null){ try { fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void testFileReader(){ FileReader fr = null; try { File file = new File("dbcp.txt"); fr = new FileReader(file); char[] c = new char[24]; int len; while((len = fr.read(c)) != -1){ String str = new String(c, 0, len); System.out.print(str); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fr != null){ try { fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
缓冲流
package com.robin.java; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.junit.Test; /* * 抽象基类 节点流(文件流) 缓冲流(处理流的一种,可以提升文件操作的效率) * InputStream FileInputStream BufferedInputStream * OutputStream FileOutputStream BufferedOutputStream(flush()) * Reader FileReader BufferedReader (readLine()) * Writer FileWriter BufferedWriter(flush()) */ public class TestBuffered { //使用BufferedInputStream和BufferedOutputStream实现非文本文件的复制 @Test public void testBufferedInputOutputStream(){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.提供读入和写出的文件 File file1 = new File("1.png"); File file2 = new File("2.png"); //2.先创建相应的节点流:FileInputStream、FileOutputStream FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); //3.将创建的节点流的对象作为形参传递给缓冲流的构造器中 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //4.具体的实现文件复制的操作 byte[] b = new byte[1024]; int len; while((len = bis.read(b)) != -1){ bos.write(b,0,len); bos.flush(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //5.关闭相应的缓冲流 if(bos != null){ try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //使用缓冲流实现文件的复制的方法 public void copyFile(String src, String dest){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.提供读入和写出的文件 File file1 = new File(src); File file2 = new File(dest); //2.先创建相应的节点流:FileInputStream、FileOutputStream FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); //3.将创建的节点流的对象作为形参传递给缓冲流的构造器中 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //4.具体的实现文件复制的操作 byte[] b = new byte[1024]; int len; while((len = bis.read(b)) != -1){ bos.write(b,0,len); bos.flush(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //5.关闭相应的缓冲流 if(bos != null){ try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void testCopyFile(){ long start = System.currentTimeMillis(); String src = "C:/Users/Robin/Desktop/1.wmv"; String dest = "C:/Users/Robin/Desktop/2.wmv"; copyFile(src,dest); long end = System.currentTimeMillis(); System.out.println("花费的时间为: " + (end - start)); //82 } @Test public void testBufferedReader(){ BufferedReader br = null; BufferedWriter bw = null; try { File file = new File("hello.txt"); File file1 = new File("h.txt"); FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file1); br = new BufferedReader(fr); bw = new BufferedWriter(fw); /*方式一 char[] c = new char[1024]; int len; while((len = br.read(c)) != -1){ String str = new String(c,0,len); System.out.print(str); } */ //方式二 /* String str; while((str = br.readLine()) != null){ System.out.println(str); } */ //读取和写入 String str; while((str = br.readLine()) != null){ bw.write(str); bw.newLine(); bw.flush(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(bw != null){ try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
转换流
转换流提供了在字节流和字符流之间的转换
Java API 提供了两个转换流:InputStreamReader和OutputStreamWriter
字节流中的数据都是字符的,转成字符流操作更高效
package com.robin.java; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import org.junit.Test; public class TestOtherStream { /* * 如何实现字节流与字符流之间的转换 * 转换流:InputStreamReader OutputStreamWriter * 编码:字符串 ----》 字节数组 * 解码:字节数组 ----》 字符串 */ @Test public void test1(){ BufferedReader br = null; BufferedWriter bw = null; try { //解码 File file = new File("dbcp.txt"); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); br = new BufferedReader(isr); //编码 File file1 = new File("dbcp1.txt"); FileOutputStream fos = new FileOutputStream(file1); OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); bw = new BufferedWriter(osw); String str; while((str = br.readLine()) != null){ bw.write(str); bw.newLine(); bw.flush(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(bw != null){ try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
标准的输入输出流
/* * 标准的输入输出流: * 标准的输出流:System.out * 标准的输入流:System.in * * * 题目: * 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。 * 然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。 */ @Test public void test2(){ BufferedReader br = null; try { InputStream is = System.in; InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); System.out.println("请输入字符串"); String str = null; while(true){ str = br.readLine(); if(str.equals("e") || str.equals("exit")){ break; } String str1 = str.toUpperCase(); System.out.println(str1); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(br != null){ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
打印流和数据流(了解)
//读取数据流 @Test public void test3(){ DataInputStream dis = null; try{ dis = new DataInputStream(new FileInputStream("Data.txt")); String str= dis.readUTF(); System.out.println(str); boolean b = dis.readBoolean(); System.out.println(b); long l = dis.readLong(); System.out.println(l); }catch(Exception e){ e.printStackTrace(); }finally{ if(dis != null){ try { dis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //数据流:用来处理基本数据类型、String、字节数组的数据:DataInputStream DataOutputStream @Test public void test2(){ DataOutputStream dos = null; try { FileOutputStream fos = new FileOutputStream("data.txt"); dos = new DataOutputStream(fos); dos.writeUTF("我爱你,而你却不知道!"); dos.writeBoolean(true); dos.writeLong(5555555555555555L); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(dos != null){ try { dos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //打印流:字节流:PrintStream 字符流:PrintWriter @Test public void test1(){ FileOutputStream fos = null; try{ fos = new FileOutputStream(new File("print.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } PrintStream ps = new PrintStream(fos,true); if(ps != null){ System.setOut(ps); } for(int i = 0; i <= 255; i++){ System.out.print((char)i); if(i % 50 == 0){ System.out.println(); } } }
对象流
public class 对象流 { /* * 对象的序列化机制:允许把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久 * 地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。 * 当其他程序获取了这种二进制流就可以恢复成原来的java对象。 */ //对象流:ObjectInputStream(反序列化) ObjectOutputStream(序列化) @Test public void test1(){ //对象的反序列化过程:将硬盘中的文件通过ObjectInputStream转换为相应的对象 ObjectInputStream ois = null; try{ ois = new ObjectInputStream(new FileInputStream("person.txt")); Person p1 = (Person)ois.readObject(); System.out.println(p1); Person p2 = (Person)ois.readObject(); System.out.println(p2); } catch(Exception e){ e.printStackTrace(); } finally{ if(ois != null){ try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void test(){ //对象的序列化过程:将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘文件中 Person p1 = new Person("AA",23,new Pet("花花")); Person p2 = new Person("BB",21,new Pet("小花")); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("person.txt")); oos.writeObject(p1); oos.flush(); oos.writeObject(p2); oos.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(oos != null){ try { oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } //要实现序列化的类: /* * 1.要求此类是可序列化的:实现Serializable接口 * 2.要求类的属性同样的要实现Serializable接口 * 3.提供一个版本号:private static final long serialVersonUID * 4.不能序列化static 和 transient 修饰的属性,不可实现序列化 */ class Person implements Serializable{ private static final long serialVersonUID = 124545124864L;//表示序列化版本标识符静态变量 String name; Integer age; Pet pet; public Person(String name,Integer age, Pet pet){ this.age = age; this.name = name; this.pet = pet; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", pet=" + pet + "]"; } } class Pet implements Serializable{ private static final long serialVersonUID = 226456153L; String name; public Pet(String name){ this.name = name; } @Override public String toString() { return "Pet [name=" + name + "]"; } }
RandomAccessFile
public class TestRandomAccessFile { /* * RandomAccessFile:支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读写文件。 * 1.既可以充当一个输入流,又可以充当一个输出流 * 2.支持从文件的开头读取、写入 * 3.支持从任意位置的读取、写入(插入) * * 构造器: * public RandomAccessFile(File file, String mode) * public RandomAccessFile(String name, String mode) * * mode : * r:以只读方式打开 * rw:打开以便读取和写入 * rwd:打开以便读取和写入;同步文件内容的更新 * rws:打开以便读取和写入;同步文件内容和元数据的更新 */ //相较于test3,更通用 @Test public void test4(){ RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File("test3.txt"),"rw"); raf.seek(14);//将指针定位到指定位置 byte[] b = new byte[10]; int len; StringBuffer sb = new StringBuffer(); while((len = raf.read(b)) != -1){ sb.append(new String(b,0,len)); } raf.seek(14); raf.write(" much ".getBytes()); raf.write(sb.toString().getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(raf != null){ try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //实现插入的效果 @Test public void test3(){ RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File("test3.txt"),"rw"); raf.seek(14);//将指针定位到指定位置 String str = raf.readLine(); // long l = raf.getFilePointer(); // System.out.println(l); raf.seek(14); raf.write(" so ".getBytes()); raf.write(str.getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(raf != null){ try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //实现的实际上是覆盖的效果 @Test public void test2(){ RandomAccessFile raf = null; try { raf = new RandomAccessFile(new File("test3.txt"),"rw"); raf.seek(14); raf.write(" very".getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(raf != null){ try { raf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //进行文件的读、写 @Test public void test(){ RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { raf1 = new RandomAccessFile(new File("test.txt"),"r"); raf2 = new RandomAccessFile(new File("test3.txt"),"rw"); byte[] b = new byte[20]; int len; while( (len = raf1.read(b)) != -1){ raf2.write(b,0,len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(raf2 != null){ try { raf2.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(raf1 != null){ try { raf1.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }