File IO (i)

Source: Internet
Author: User
Tags object serialization prepare readline stub

Data flow is a linear and ordered data object with a certain byte length and direction.

In Unix/linux, the large and lowercase letters in the path represent different paths, while the Windows operating system ignores case. Two constants of the PS. File class: File.separator in Unix system value is/, in Windows system value is \\;file.pathseparator in Unix system value is:, in Windows system value is;.

Classes and interfaces for Java Stream operations: (the discussion here has been taken from elsewhere, but the notes were not recorded)
A file class that encapsulates files and folders in a file system. The file class holds various metadata information about the files or directories, including the file name, file length, last modified time, and whether it is readable. The file class also has the path name to get the current file, to determine if the specified file exists, to obtain a list of files in the current directory, and to create, delete files and directories.
The Randomaccessfile class encapsulates the byte stream and also encapsulates a buffer (a character array) that operates on the data in a character array through an internal pointer, manipulating only the file. The constructor receives two types: the file path (string form) and the file object. When you instantiate a Randomaccessfile object, you can specify an action mode (such as R, RW) that is automatically created if the file that is being manipulated does not exist, and if the file exists and the write data does not specify a location, it is written from the beginning, overwriting the original content.
The byte stream is also called the raw data, which requires the user to read it and do the corresponding conversion, which is processed by InputStream, OutputStream and its subclasses; the implementation of character streams is based on automatic conversion, which is automatically converted to characters according to the JVM default encoding when reading data, by writer, Reader and its subclass processing. The difference between a stream of bytes and the character streams: read-write units, bytes (byte), characters (two-byte Unicode); Unlike processing objects, a byte stream can handle all data types (such as pictures), reads bytes from the machine store, and the character streams convert bytes into Unicode characters by the JVM. So you can only handle character types, which is better for text support. PS. Inputstream,outputstream,reader,writer are abstract classes, so they cannot be directly new.

Further discussion on the difference between byte streams and character stream: A detailed source reference http://blog.csdn.net/cynhafa/article/details/6882061
    The byte stream does not use a buffer (memory) when it operates, it is directly manipulated by the file itself, and the character streams use a buffer in the operation, and then manipulate the file through the buffer. Two examples to illustrate:
    use a byte stream to not close execution

Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;

public class Outputwriter {

    /**
     * @param args
     * @throws ioexception
    /public static void main ( String[] args) throws IOException {/
        /TODO auto-generated Method Stub
        //1th step: Use the file class to find a filename '
        f = new Fil E ("D:" + File.separator + "test.txt"); Declares the file object
        //step 2nd: Instantiating the parent class object OutputStream out
        = null through subclasses;
        Prepare an Output object out
        = new FileOutputStream (f);
        Instantiation through Object polymorphism
        //Step 3rd: Write operations
        String str = "Hello world!!!";
        Prepares a string
        byte b[] = Str.getbytes ();
        String to byte array
        out.write (b);
        Content output
        //4th: Turn off output stream
        //Out.close ();
        Not closing
    }
} at this time

At this point the test file has content for Hello world ...
Using character streams does not close execution

 import java.io.File; import java.io.FileWriter; import java.io.IOException; import Java.io.Writer; public class Outputwriter {/** * @param args * @throws ioexception/public static void main (STR Ing[] args) throws IOException {//TODO auto-generated Method Stub//1th step: Use the file class to find a filename f =
        New File ("D:" + File.separator + "test.txt")//Declare File object//2nd step: Instantiate the parent class object Writer out = null through subclasses;
        Prepare an Output object out = new FileWriter (f);
        Instantiation through object polymorphism//step 3rd: Write operations String str = "Hello world!!!";
        Prepares a string out.write (str);
        Content Output//4th step: Turn off output stream//Out.close (); Not close}} 
at this time

View the test file at this time without any content.
A character stream operation uses a buffer, and when the character stream is closed, the contents of the buffer are forced to output, but if the program is not closed and the character stream is not closed in the program, the contents of the buffer cannot be exported. If you want to output all the contents of a character stream when you do not close it, you can do so by using the flush () method in the writer class.
The process of converting a byte into a character stream is actually byte[] into a string, method public string (byte bytes[], String charsetname), and a key parameter character set encoding in the parameter, which is usually omitted. The system uses the OS lang, and the method byte[] String.getbytes (String charsetname) is the same when the character is converted to a byte stream, which is actually a string to byte[.

A buffer in a file operation that refers to a specified amount of memory used to hold data in a file IO data stream, and the purpose of buffering is to increase the efficiency of writing or reading data frequently in code. When any of the following conditions are met, the data flow of the buffer is read or written out to the output device by the batch program: the buffer is full, the file is closed (call the Close () method), and the buffer is refreshed (call the Flush () method).

File IO Exceptions are check exceptions, which means that the code must provide a mechanism for handling file IO exceptions, either by using Try-catch program blocks to handle exceptions, or by using throw to propagate exceptions. File IO includes exceptions that can occur when ioexception--handles an IO error, or an exception that is thrown when an eofexception--program attempts to read data that is out of file scope; filenotfoundexception-- An exception that is thrown when a program attempts to open a file that does not exist. IOException are super classes of eofexception and FileNotFoundException, and their superclass is exception until throwable.

Although text files occupy more memory than binaries, text files apply IO processing of string-dominated data streams, and the benefits are intuitive and easy to manipulate. The Java.io package provides two sets of API classes, writer and reader-superclass, for IO processing and manipulation of text files.
In the specific text output code, follow the sequence from file to buffer, and then to the printed text file. Such as:

Printerwriter
    -->bufferedwriter (optional)
        -->filewriter

If you do not need to apply buffering, you can use PrintWriter (file file) to create a file object directly for the output of a text file.

Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;

Import Java.io.PrintWriter; public class Outputwriter {/** * @param args * @throws ioexception/public static void main (STR Ing[] args) throws IOException {//TODO auto-generated method Stub file = new File ("D:" + file.separ
        Ator + "test.txt"); Java.io.FileWriter.FileWriter (File File, Boolean append) throws IOException//Append if True, then bytes would Be written to the "end of" the file rather than the beginning printwriter outprintwriter = new PrintWriter (New Buffe
        Redwriter (New FileWriter (file, true));
        Outprintwriter.print ("Version:" + 1.01);
        Outprintwriter.println ();
        Outprintwriter.write ("File name:test.txt");
        Outprintwriter.println ("Line of Change here");
        Outprintwriter.append ("We ll see!"); Outprintwriter.close (); Outprintwriter.flush () can also be}}

The above program runs the result, the Test.txt file in D disk writes the following content

The read-in operation of the system preset text file is buffered input, and its common pattern is:

BufferedReader
    -->filereader

Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileReader;

Import java.io.IOException; public class Inputreader {/** * @param args * @throws ioexception/public static void main (STR Ing[] args) throws IOException {//TODO auto-generated method Stub file = new File ("D:" +file.separat
        or+ "Test.txt");
        BufferedReader in = new BufferedReader (new FileReader (file));
         /* Use ReadLine () to read the file content * String line = In.readline ();
         * while (line!= null) {* SYSTEM.OUT.PRINTLN (line);
         * line = In.readline ();
         * In.close ();
        * * */String line = ""; int ch = in.read ();
            Read a character while (Ch!=-1) {//read () reads to the end of the file, its read content is-1 line + = (char) ch;
                if (ch = = ' \ n ') {//encountered a newline character, output System.out.print (line);
            line = "";
  else if (ch = = ' 1 ') {//encounters ' 1 ', skipping 3 characters in.skip (3);          ch = in.read ();
        } System.out.print (line);
    In.close (); Run Result: Version:1 File name:test.txt here for line We ll see!

The general mode for binary file output operations is:

DataOutputStream
    -->bufferedoutputstream (optional, but recommended)
        -->fileoutputstream
 Import java.io.BufferedOutputStream import java.io.DataOutputStream import java.io.File; import
Java.io.FileOutputStream;

Import java.io.IOException; public class OutputWriter2 {public static void main (string[] args) throws IOException {File File = new file (
        "D:" + file.separator + "test2.txt");
        DataOutputStream out = new DataOutputStream (new Bufferedoutputstream (new FileOutputStream (file));   Out.writeboolean (TRUE);        1 bytes Out.writechar (65);       2 bytes Out.writechar (' A ');   2 bytes out.writechars ("Java");        8 bytes out.writebyte (99);       1 bytes out.writebyte (' B '); 1 bytes out.writebytes ("coding");     6 bytes Out.writeutf ("Java");
        6 bytes out.close ();
    System.out.println ("File Size:" +out.size () + "bytes"); }
}

With respect to the Writebytes (string s) and writeUTF (string s) in the above program, Writebytes writes a eight-bit high of eight bits of each character in the string to write bytes low, so writebytes ("coding") writes 6 bytes, WriteByte Similarly, write (' B ') also loses the high byte of the character ' B '; writeUTF writes the string in UTF-8 format, which first represents the number of bytes in the string in two bytes, and then writes the character in UTF-8 format (for characters that can be represented by ASCII code , UTF-8 also uses a generic byte to represent it, so writeUTF ("Java") writes 2+4 bytes.

Binary file input Operation General mode:

DataInputStream
    -->bufferedinputstream (optional, recommended)
        -->fileinputstream

Import Java.io.BufferedInputStream;
Import Java.io.DataInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;

Import java.io.IOException; public class InputReader2 {/** * @param args * @throws ioexception/public static void main (STR Ing[] args) throws IOException {//TODO auto-generated method Stub file = new File ("D:" + file.separ
        Ator + "Test2.txt");
        DataInputStream in = new DataInputStream (new Bufferedinputstream (new FileInputStream (file));
        Boolean flag = In.readboolean ();
        Char ch1 = In.readchar ();
        Char CH2 = In.readchar ();
        String name1 = "";
        for (int i = 0; i < 4; i++) {name1 + = In.readchar ();
        BYTE B1 = In.readbyte ();
        byte B2 = In.readbyte ();
        Byte[] bs = new byte[6];
        for (int i = 0; i < 6; i++) {Bs[i] = In.readbyte ();
        String name2 = In.readutf ();
 In.close ();       SYSTEM.OUT.PRINTLN (flag);
        System.out.println (CH1);
        System.out.println (CH2);
        System.out.println (NAME1);
        System.out.println (B1);
        System.out.println (B2);
        SYSTEM.OUT.PRINTLN (BS);
    System.out.println (name2); }
}

Note: Read is read in the order in which it was written. Results of operation of the above program:

True
a
a
java
(b@c17164
java


This one is first written here, next write object serialization IO and Randomaccessfile

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.