java常用类解析六:IO系统文件读写工具类

来源:互联网 发布:看门狗优化补丁 编辑:程序博客网 时间:2024/05/22 11:32

几个文件读写的工具类:文本文件读写、二进制文件读写、对象读写。其中对象读写工具类有错误,在试图进行多个对象读取时,读第二个对象就抛出异常,这是为什么?此外怎样把一个存放对象的文件中所有的对象读出来?

这个问题已经解决,非常感谢Aguo的文章:自定义ObjectOutputStream,解决追加写入后,读取错误的问题 。在这篇文章中我找到了答案,同时对作者的源代码添加了一些注解。解决方案请看文章最后。

1、文本文件读写工具类

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.FileReader;  
  6. import java.io.FileWriter;  
  7. import java.io.IOException;  
  8.   
  9. /** 
  10.  * 此工具类用于文本文件的读写 
  11.  *  
  12.  * @author Touch 
  13.  */  
  14. public class TextFile {  
  15.     // 读取指定路径文本文件  
  16.     public static String read(String filePath) {  
  17.         StringBuilder str = new StringBuilder();  
  18.         BufferedReader in = null;  
  19.         try {  
  20.             in = new BufferedReader(new FileReader(filePath));  
  21.             String s;  
  22.             try {  
  23.                 while ((s = in.readLine()) != null)  
  24.                     str.append(s + '\n');  
  25.             } finally {  
  26.                 in.close();  
  27.             }  
  28.         } catch (IOException e) {  
  29.             // TODO Auto-generated catch block  
  30.             e.printStackTrace();  
  31.         }  
  32.         return str.toString();  
  33.     }  
  34.   
  35.     // 写入指定的文本文件,append为true表示追加,false表示重头开始写,  
  36.     //text是要写入的文本字符串,text为null时直接返回  
  37.     public static void write(String filePath, boolean append, String text) {  
  38.         if (text == null)  
  39.             return;  
  40.         try {  
  41.             BufferedWriter out = new BufferedWriter(new FileWriter(filePath,  
  42.                     append));  
  43.             try {  
  44.                 out.write(text);  
  45.             } finally {  
  46.                 out.close();  
  47.             }  
  48.         } catch (IOException e) {  
  49.             // TODO Auto-generated catch block  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53. }  
  54. </span>  

 

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util;  
  2.   
  3. public class TestTextFile {  
  4.     public static void main(String[] args) {  
  5.         TextFile.write("file/textfile.txt"false,  
  6.                 "这是一个文本文件的读写测试\nTouch\n刘海房\n男\n");  
  7.         TextFile.write("file/textfile.txt"true"武汉工业学院\n软件工程");  
  8.         System.out.println(TextFile.read("file/textfile.txt"));  
  9.     }  
  10. }  
  11. </span>  

 

2、二进制文件读写工具类

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8.   
  9. /** 
  10.  * 此工具类用于二进制文件的读写 
  11.  *  
  12.  * @author Touch 
  13.  */  
  14. public class BinaryFile {  
  15.     // 把二进制文件读入字节数组,如果没有内容,字节数组为null  
  16.     public static byte[] read(String filePath) {  
  17.         byte[] data = null;  
  18.         try {  
  19.             BufferedInputStream in = new BufferedInputStream(  
  20.                     new FileInputStream(filePath));  
  21.             try {  
  22.                 data = new byte[in.available()];  
  23.                 in.read(data);  
  24.             } finally {  
  25.                 in.close();  
  26.             }  
  27.         } catch (IOException e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.         return data;  
  31.     }  
  32.   
  33.     // 把字节数组为写入二进制文件,数组为null时直接返回  
  34.     public static void write(String filePath, byte[] data) {  
  35.         if (data == null)  
  36.             return;  
  37.         try {  
  38.             BufferedOutputStream out = new BufferedOutputStream(  
  39.                     new FileOutputStream(filePath));  
  40.             try {  
  41.                 out.write(data);  
  42.             } finally {  
  43.                 out.close();  
  44.             }  
  45.         } catch (IOException e) {  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49. }  
  50. </span>  


 

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. public class TestBinaryFile {  
  6.     public static void main(String[] args) {  
  7.         BinaryFile.write("file/binaryfile.dat"new byte[] { 123456,  
  8.                 78910'a''b''c' });  
  9.         byte[] data = BinaryFile.read("file/binaryfile.dat");  
  10.         System.out.println(Arrays.toString(data));  
  11.     }  
  12. }  
  13. </span>  


 

3、对象读写工具类(有问题,在读取多个对象时有问题,怎样把一个对象文件中的所有对象读出来?)

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.ObjectInputStream;  
  7. import java.io.ObjectOutputStream;  
  8.   
  9. /** 
  10.  * 此类用于对象的读写 
  11.  *  
  12.  * @author Touch 
  13.  */  
  14. public class ObjectFile {  
  15.     // 把一个对象写入文件,isAppend为true表示追加方式写,false表示重新写  
  16.     public static void write(String filePath, Object o, boolean isAppend) {  
  17.         if (o == null)  
  18.             return;  
  19.         try {  
  20.             ObjectOutputStream out = new ObjectOutputStream(  
  21.                     new FileOutputStream(filePath, isAppend));  
  22.             try {  
  23.                 out.writeObject(o);  
  24.             } finally {  
  25.                 out.close();  
  26.             }  
  27.         } catch (IOException e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.     }  
  31.   
  32.     // 把一个对象数组写入文件,isAppend为true表示追加方式写,false表示重新写  
  33.     public static void write(String filePath, Object[] objects, boolean isAppend) {  
  34.         if (objects == null)  
  35.             return;  
  36.         try {  
  37.             ObjectOutputStream out = new ObjectOutputStream(  
  38.                     new FileOutputStream(filePath, isAppend));  
  39.             try {  
  40.                 for (Object o : objects)  
  41.                     out.writeObject(o);  
  42.             } finally {  
  43.                 out.close();  
  44.             }  
  45.         } catch (IOException e) {  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49.   
  50.     // 读取对象,返回一个对象  
  51.     public static Object read(String filePath) {  
  52.         Object o = null;  
  53.         try {  
  54.             ObjectInputStream in = new ObjectInputStream(new FileInputStream(  
  55.                     filePath));  
  56.             try {  
  57.                 o = in.readObject();  
  58.             } finally {  
  59.                 in.close();  
  60.             }  
  61.         } catch (Exception e) {  
  62.             e.printStackTrace();  
  63.         }  
  64.         return o;  
  65.     }  
  66.   
  67.     // 读取对象,返回一个对象数组,count表示要读的对象的个数  
  68.     public static Object[] read(String filePath, int count) {  
  69.         Object[] objects = new Object[count];  
  70.         try {  
  71.             ObjectInputStream in = new ObjectInputStream(new FileInputStream(  
  72.                     filePath));  
  73.             try {  
  74.                 for (int i = 0; i < count; i++) {  
  75.                     //第二次调用in.readObject()就抛出异常,这是为什么?  
  76.                     objects[i] = in.readObject();  
  77.                 }  
  78.             } finally {  
  79.                 in.close();  
  80.             }  
  81.         } catch (Exception e) {  
  82.             e.printStackTrace();  
  83.         }  
  84.         return objects;  
  85.     }  
  86. }  
  87. </span>  


 

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class TestObjectFile {  
  6.     public static void main(String[] args) {  
  7.         ObjectFile.write("file/object1"new Person(), false);  
  8.         ObjectFile.write("file/object1"new Person(), true);  
  9.         ObjectFile.write("file/object1"new Person[] { new Person("Touch"1),  
  10.                 new Person("Rainbow"0), new Person() }, true);  
  11.         for (Object o : ObjectFile.read("file/object1"5))  
  12.             ((Person) o).display();  
  13.     }  
  14. }  
  15.   
  16. class Person implements Serializable {  
  17.     private String name = "刘海房";  
  18.     private int sex = 0;  
  19.   
  20.     Person(String name, int sex) {  
  21.         this.name = name;  
  22.         this.sex = sex;  
  23.     }  
  24.   
  25.     Person() {  
  26.     }  
  27.   
  28.     void display() {  
  29.         System.out.println("my name is :" + name);  
  30.         String s = (sex == 0) ? "男" : "女";  
  31.         System.out.println("性别:" + s);  
  32.     }  
  33. }</span>  


4、对象读写工具类(解决了3中的问题,能够写入及读取多个对象)

          3中到底问题出在哪呢?先来看一段ObjectOutputStream构造方法的源代码,此源代码来自jdk1.6版。

[java] view plaincopy
  1. <span style="font-size:16px;">    public ObjectOutputStream(OutputStream out) throws IOException {  
  2.     verifySubclass();  
  3.     bout = new BlockDataOutputStream(out);  
  4.     handles = new HandleTable(10, (float3.00);  
  5.     subs = new ReplaceTable(10, (float3.00);  
  6.     enableOverride = false;  
  7.     </span><span style="font-size:16px;"><span style="color:#ff0000;">writeStreamHeader();  
  8. </span> bout.setBlockDataMode(true);  
  9.         if (extendedDebugInfo) {  
  10.         debugInfoStack = new DebugTraceInfoStack();  
  11.     } else {  
  12.         debugInfoStack = null;  
  13.         }     
  14.     }</span>  


这段代码中我们只需要关注writeStreamHeader();方法,这个方法在源代码中的解释是

[java] view plaincopy
  1. <span style="font-size:16px;"/** 
  2.      * The writeStreamHeader method is provided so subclasses can append or 
  3.      * prepend their own header to the stream.  It writes the magic number and 
  4.      * version to the stream. 
  5.      * 
  6.      * @throws  IOException if I/O errors occur while writing to the underlying 
  7.      *      stream 
  8.      */</span>  

也就是说我们打开(new)一个ObjectOutputStream的时候,这个ObjectOutputStream流中就已经被写入了一些信息,这些信息会写入到我们的文件中。在第一次写入文件时,这些头部信息时需要的,因为ObjectInputStream读的时候会帮我们过滤掉。但是当我们追加写入一个文件时,这些头部信息也会写入文件中,读取的时候只会把文件第一次出现的头部信息过滤掉,并不会把文件中间的头部信息也过滤掉,这就是问题的根源所在。

      怎么解决呢?正如lichong_87提到的

      一、可以在每次写入的时候把文件中所有对象读出来,然后重新写入,这种方法效率比较低。

      二、如果不是第一次写入文件,在写入时去掉头部信息,怎么去掉呢?头部信息是在writeStreamHeader();方法中写入的,所以我们可以通过继承ObjectOutputStream来覆盖这个方法,如果不是第一次写入文件,这个方法什么也不做。

     下面是第二种解决方案的源代码及测试

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util.io;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.ObjectOutputStream;  
  6. import java.io.OutputStream;  
  7.   
  8. /** 
  9.  * 此类继承ObjectOutputStream,重写writeStreamHeader()方法,以实现追加写入时去掉头部信息 
  10.  */  
  11. public class MyObjectOutputStream extends ObjectOutputStream {  
  12.     private static File f;  
  13.   
  14.     // writeStreamHeader()方法是在ObjectOutputStream的构造方法里调用的  
  15.     // 由于覆盖后的writeStreamHeader()方法用到了f。如果直接用此构造方法创建  
  16.     // 一个MyObjectOutputStream对象,那么writeStreamHeader()中的f是空指针  
  17.     // 因为f还没有初始化。所以这里采用单态模式  
  18.     private MyObjectOutputStream(OutputStream out, File f) throws IOException,  
  19.             SecurityException {  
  20.         super(out);  
  21.     }  
  22.   
  23.     // 返回一个MyObjectOutputStream对象,这里保证了new MyObjectOutputStream(out, f)  
  24.     // 之前f已经指向一个File对象  
  25.     public static MyObjectOutputStream newInstance(File file, OutputStream out)  
  26.             throws IOException {  
  27.         f = file;// 本方法最重要的地方:构建文件对象,两个引用指向同一个文件对象  
  28.         return new MyObjectOutputStream(out, f);  
  29.     }  
  30.   
  31.     @Override  
  32.     protected void writeStreamHeader() throws IOException {  
  33.         // 文件不存在或文件为空,此时是第一次写入文件,所以要把头部信息写入。  
  34.         if (!f.exists() || (f.exists() && f.length() == 0)) {  
  35.             super.writeStreamHeader();  
  36.         } else {  
  37.             // 不需要做任何事情  
  38.         }  
  39.     }  
  40. }  
  41. </span>  


 

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util.io;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.ObjectInputStream;  
  8.   
  9. /** 
  10.  * 此类用于对象的读写 
  11.  *  
  12.  * @author Touch 
  13.  */  
  14. public class ObjectFile {  
  15.     // 把一个对象写入文件,isAppend为true表示追加方式写,false表示重新写  
  16.     public static void write(String filePath, Object o, boolean isAppend) {  
  17.         if (o == null)  
  18.             return;  
  19.         try {  
  20.             File f = new File(filePath);  
  21.             MyObjectOutputStream out = MyObjectOutputStream.newInstance(f,  
  22.                     new FileOutputStream(f, isAppend));  
  23.             try {  
  24.                 out.writeObject(o);  
  25.             } finally {  
  26.                 out.close();  
  27.             }  
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32.   
  33.     // 把一个对象数组写入文件,isAppend为true表示追加方式写,false表示重新写  
  34.     public static void write(String filePath, Object[] objects, boolean isAppend) {  
  35.         if (objects == null)  
  36.             return;  
  37.         try {  
  38.             File f = new File(filePath);  
  39.             MyObjectOutputStream out = MyObjectOutputStream.newInstance(f,  
  40.                     new FileOutputStream(f, isAppend));  
  41.             try {  
  42.                 for (Object o : objects)  
  43.                     out.writeObject(o);  
  44.             } finally {  
  45.                 out.close();  
  46.             }  
  47.         } catch (IOException e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51.   
  52.     // 读取对象,返回一个对象  
  53.     public static Object read(String filePath) {  
  54.         Object o = null;  
  55.         try {  
  56.             ObjectInputStream in = new ObjectInputStream(new FileInputStream(  
  57.                     filePath));  
  58.             try {  
  59.                 o = in.readObject();  
  60.             } finally {  
  61.                 in.close();  
  62.             }  
  63.         } catch (Exception e) {  
  64.             e.printStackTrace();  
  65.         }  
  66.         return o;  
  67.     }  
  68.   
  69.     // 读取对象,返回一个对象数组,count表示要读的对象的个数  
  70.     public static Object[] read(String filePath, int count) {  
  71.         Object[] objects = new Object[count];  
  72.         try {  
  73.             ObjectInputStream in = new ObjectInputStream(new FileInputStream(  
  74.                     filePath));  
  75.             try {  
  76.                 for (int i = 0; i < count; i++) {  
  77.                       
  78.                     objects[i] = in.readObject();  
  79.                 }  
  80.             } finally {  
  81.                 in.close();  
  82.             }  
  83.         } catch (Exception e) {  
  84.             e.printStackTrace();  
  85.         }  
  86.         return objects;  
  87.     }  
  88. }  
  89. </span>  


 

[java] view plaincopy
  1. <span style="font-size:16px;">package mine.util.io;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class TestObjectFile {  
  6.     public static void main(String[] args) {  
  7.         ObjectFile.write("file/t.dat"new Person(), false);  
  8.         ObjectFile.write("file/t.dat"new Person(), true);  
  9.         ObjectFile.write("file/t.dat"new Person[] { new Person("Touch"1),  
  10.                 new Person("Rainbow"0), new Person() }, true);  
  11.         for (Object o : ObjectFile.read("file/t.dat"5))  
  12.             ((Person) o).display();  
  13.     }  
  14. }  
  15.   
  16. class Person implements Serializable {  
  17.     private static final long serialVersionUID = 1L;  
  18.     private String name = "刘海房";  
  19.     private int sex = 0;  
  20.   
  21.     Person(String name, int sex) {  
  22.         this.name = name;  
  23.         this.sex = sex;  
  24.     }  
  25.   
  26.     Person() {  
  27.     }  
  28.   
  29.     void display() {  
  30.         System.out.println("my name is :" + name);  
  31.         String s = (sex == 0) ? "男" : "女";  
  32.         System.out.println("性别:" + s);  
  33.     }  
  34. }</span>  


运行结果:

my name is :刘海房
性别:男
my name is :刘海房
性别:男
my name is :Touch
性别:女
my name is :Rainbow
性别:男
my name is :刘海房
性别:男