Common Java classes: I/O system file read/write tools

Source: Internet
Author: User

Several file read/write tools: text file read/write, binary file read/write, object read/write. The object reading/writing tool class has an error. When trying to read multiple objects, an exception is thrown when reading the second object. Why? In addition, how can we read all objects in a file that stores objects?

This problem has been solved. Thanks to aguo's article: The Custom objectoutputstream solves the problem of Reading Errors after append writing. In this article, I found the answer and added some annotations to the author's source code. For the solution, see the end of the article.

1. Text File read/write Tool

Package mine. util; import Java. io. bufferedreader; import Java. io. bufferedwriter; import Java. io. filereader; import Java. io. filewriter; import Java. io. ioexception;/*** this tool class is used for reading and writing text files ** @ author touch */public class textfile {// read the public static string read (string filepath) text file in the specified path) {stringbuilder STR = new stringbuilder (); bufferedreader in = NULL; try {In = new bufferedreader (New filereader (filepath); stri Ng s; try {While (S = in. Readline ())! = NULL) Str. append (S + '\ n');} finally {In. close () ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} return Str. tostring ();} // write the specified text file. If the value of append is true, append is append. If the value of false is false, write again. // text is the text string to be written, if text is null, public static void write (string filepath, Boolean append, string text) {If (text = NULL) return; try {bufferedwriter out = new bufferedwriter (New filewriter (filepath, append); try {out. write (text);} finally {out. close () ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

 

Package mine. util; public class testtextfile {public static void main (string [] ARGs) {textfile. write ("file/textfile.txt", false, "this is a text file read/write test \ ntouch \ n bangs room \ n male \ n"); textfile. write ("file/textfile.txt", true, "Wuhan Institute of industry \ n software engineering"); system. out. println (textfile. read ("file/textfile.txt "));}}

 

2. Binary file read/write Tool

Package mine. util; import Java. io. bufferedinputstream; import Java. io. bufferedoutputstream; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception;/*** this tool class is used to read and write binary files ** @ author touch */public class binaryfile {// read binary files into byte arrays. If no content exists, the byte array is nullpublic static byte [] Read (string filepath) {byte [] DATA = NULL; try {bufferedinputstream in = new bufferedinputstream (New fileinputstream (filepath )); try {DATA = new byte [in. available ()]; In. read (data);} finally {In. close () ;}} catch (ioexception e) {e. printstacktrace ();} return data;} // write the byte array to a binary file. If the array is null, the public static void write (string filepath, byte [] data) is directly returned) {If (Data = NULL) return; try {bufferedoutputstream out = new bufferedoutputstream (New fileoutputstream (filepath); try {out. write (data);} finally {out. close () ;}} catch (ioexception e) {e. printstacktrace ();}}}

 

package mine.util;import java.util.Arrays;public class TestBinaryFile {public static void main(String[] args) {BinaryFile.write("file/binaryfile.dat", new byte[] { 1, 2, 3, 4, 5, 6,7, 8, 9, 10, 'a', 'b', 'c' });byte[] data = BinaryFile.read("file/binaryfile.dat");System.out.println(Arrays.toString(data));}}

 

3. Object read/write tool class (if there is a problem, when reading multiple objects, how can we read all objects in an object file ?)

Package mine. util; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. objectinputstream; import Java. io. objectoutputstream;/*** this class is used for reading and writing objects ** @ author touch */public class objectfile {// write an object to a file. If isappend is true, it indicates the append mode, false indicates that public static void write (string filepath, object o, Boolean isappend) {If (O = NULL) return; try {objectoutputstream out = New objectoutputstream (New fileoutputstream (filepath, isappend); try {out. writeobject (o);} finally {out. close () ;}} catch (ioexception e) {e. printstacktrace () ;}/// write an object array to a file. If isappend is set to true, the append method is used. If false, the public static void write (string filepath, object [] objects, boolean isappend) {If (Objects = NULL) return; try {objectoutputstream out = new objectoutputstream (New fileoutputstream (filepath, Isa Ppend); try {for (Object O: Objects) out. writeobject (o);} finally {out. close () ;}} catch (ioexception e) {e. printstacktrace () ;}/// read object, returns an object public static object read (string filepath) {object o = NULL; try {objectinputstream in = new objectinputstream (New fileinputstream (filepath); try {o = in. readobject ();} finally {In. close () ;}} catch (exception e) {e. printstacktrace () ;}return o ;}// read the object and return an array of objects., Count indicates the number of objects to be read. Public static object [] Read (string filepath, int count) {object [] objects = new object [count]; try {objectinputstream in = new objectinputstream (New fileinputstream (filepath); try {for (INT I = 0; I <count; I ++) {// The second call in. readobject () throws an exception. Why? Objects [I] = in. readobject () ;}} finally {In. close () ;}} catch (exception e) {e. printstacktrace () ;}return objects ;}}

 

Package mine. util; import Java. io. serializable; public class testobjectfile {public static void main (string [] ARGs) {objectfile. write ("file/object1", new person (), false); objectfile. write ("file/object1", new person (), true); objectfile. write ("file/object1", new person [] {new person ("Touch", 1), new person ("Rainbow", 0), new person ()}, true); For (Object O: objectfile. read ("file/object1", 5) (person) O ). display () ;}} class person implements serializable {private string name = ""; private int sex = 0; person (string name, int sex) {This. name = Name; this. sex = sex;} person () {} void display () {system. out. println ("My name is:" + name); string S = (sex = 0 )? "Male": "female"; system. Out. println ("Gender:" + S );}}

4. Object read/write tool class (solves the problem in step 3 and can write and read multiple objects)

3. What is the problem? Let's take a look at the source code of the objectoutputstream constructor. The source code is from JDK.

    public ObjectOutputStream(OutputStream out) throws IOException {verifySubclass();bout = new BlockDataOutputStream(out);handles = new HandleTable(10, (float) 3.00);subs = new ReplaceTable(10, (float) 3.00);enableOverride = false;writeStreamHeader();bout.setBlockDataMode(true);        if (extendedDebugInfo) {    debugInfoStack = new DebugTraceInfoStack();} else {    debugInfoStack = null;        }       }

In this Code, we only need to pay attention to the writestreamheader (); method. The explanation of this method in the source code is

 /**     * The writeStreamHeader method is provided so subclasses can append or     * prepend their own header to the stream.  It writes the magic number and     * version to the stream.     *     * @throwsIOException if I/O errors occur while writing to the underlying     * stream     */

That is to say, when we open (new) An objectoutputstream, some information has been written into this objectoutputstream, which will be written into our file. This header information is required when a file is written for the first time, because the objectinputstream will be filtered out during reading. However, when we append a file, the header information will also be written to the file. When we read the file, we will only filter out the header information that appears for the first time, the header information in the file is not filtered out, which is the root cause of the problem.

How can this problem be solved? As lichong_87 mentioned

1. You can read all objects in the file and write them again at each write. This method is less efficient.

2. If it is not the first time a file is written, how can I remove the header information? The header information is written in the writestreamheader (); method, so we can inherit objectoutputstream to overwrite this method. If it is not the first time the file is written, this method will not do anything.

The following is the source code and test of the second solution.

Package mine. util. io; import Java. io. file; import Java. io. ioexception; import Java. io. objectoutputstream; import Java. io. outputstream;/*** this class inherits objectoutputstream and overwrites the writestreamheader () method to remove the header information during append write */public class myobjectoutputstream extends objectoutputstream {Private Static file F; // The writestreamheader () method is called in the constructor method of objectoutputstream. // F is used because of the covered writestreamheader () method. If you use this constructor to create a // myobjectoutputstream object, F in writestreamheader () is a null pointer // because f has not been initialized yet. Therefore, the single-State mode private myobjectoutputstream (outputstream out, file F) throws ioexception, securityexception {super (out) ;}// returns a myobjectoutputstream object. The new myobjectoutputstream (Out, f) // previously, F has pointed to a file object public static myobjectoutputstream newinstance (File file, outputstream out) throws ioexception {f = file; // the most important part of this method: build a file object. The two references point to the same file object return New myobjectoutputstream (Out, f);} @ overrideprotected void Writestreamheader () throws ioexception {// the file does not exist or the file is empty. This is the first time the file is written, so you need to write the header information. If (! F. exists () | (F. exists () & F. length () = 0) {super. writestreamheader ();} else {// No Need To Do Anything }}}


 

Package mine. util. io; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. objectinputstream;/*** this class is used to read and write objects ** @ author touch */public class objectfile {// write an object to a file. If isappend is true, it indicates the append mode, false indicates re-writing public static void write (string filepath, object o, Boolean isappend) {If (O = NULL) return; try {file F = new file (filepath ); myobjectoutputstream out = myobjectoutputstream. newinstance (F, new fileoutputstream (F, isappend); try {out. writeobject (o);} finally {out. close () ;}} catch (ioexception e) {e. printstacktrace () ;}/// write an object array to a file. If isappend is set to true, the append method is used. If false, the public static void write (string filepath, object [] objects, boolean isappend) {If (Objects = NULL) return; try {file F = new file (filepath); myobjectoutputstream out = myobjectoutputstream. newinstance (F, new fileoutputstream (F, isappend); try {for (Object O: Objects) out. writeobject (o);} finally {out. close () ;}} catch (ioexception e) {e. printstacktrace () ;}/// read object, returns an object public static object read (string filepath) {object o = NULL; try {objectinputstream in = new objectinputstream (New fileinputstream (filepath); try {o = in. readobject ();} finally {In. close () ;}} catch (exception e) {e. printstacktrace () ;}return o ;}// read object. An array of objects is returned. Count indicates the number of objects to be read. Public static object [] Read (string filepath, int count) {object [] objects = new object [count]; try {objectinputstream in = new objectinputstream (New fileinputstream (filepath); try {for (INT I = 0; I <count; I ++) {objects [I] = in. readobject () ;}} finally {In. close () ;}} catch (exception e) {e. printstacktrace () ;}return objects ;}}


 

Package mine. util. io; import Java. io. serializable; public class testobjectfile {public static void main (string [] ARGs) {objectfile. write ("file/t. dat ", new person (), false); objectfile. write ("file/t. dat ", new person (), true); objectfile. write ("file/t. dat ", new person [] {new person (" Touch ", 1), new person (" Rainbow ", 0), new person ()}, true ); for (Object O: objectfile. read ("file/t. dat ", 5) (person) O ). d Isplay () ;}} class person implements serializable {Private Static final long serialversionuid = 1l; private string name = ""; private int sex = 0; person (string name, int sex) {This. name = Name; this. sex = sex;} person () {} void display () {system. out. println ("My name is:" + name); string S = (sex = 0 )? "Male": "female"; system. Out. println ("Gender:" + S );}}

Running result:

My name is: liuhaicang
Gender: male
My name is: liuhaicang
Gender: male
My name is: Touch
Gender: Female
My name is: rainbow
Gender: male
My name is: liuhaicang
Gender: male

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.