Java I/O

Source: Internet
Author: User

In the Java array, the variables and objects stored in the data is temporary, in order to ensure the permanent storage of data, you need to save it in the hard disk file, Java I/O technology can be saved to the hard disk text file. Before we know the "flow", we need to look at what the computer's memory and hard disk are.

Memory is one of the computer's data storage devices, used to store the running program and data, can directly exchange information with the operator and controller. Memory is one of the most important parts of a computer, and it is a bridge to communicate with the CPU. All the programs in the computer are run in memory, which is used to temporarily store the operational data in the CPU and the data exchanged with external memory such as the hard disk. As long as the computer is running, the CPU will transfer the data needed for operation into memory and the CPU will transmit the result when the operation is complete. The hard disk is a computer's important external storage device, the computer operating system, application software, documents, data, etc., can be stored on the hard disk.

Knowing the difference between memory and hard disk, look at the concept of "stream".

The picture above shows the process of downloading something we normally do. In relation to memory, "flow" can be divided into input stream and output stream according to direction, the input stream is in the direction of memory, the output stream is the direction of leaving memory. According to the format of reading data, memory can be divided into character stream and character stream, byte stream is read data in bytes, usually used to read pictures, sound, video and other binary files, and character stream is read data in characters format, can be used to read plain text files, such as the TXT file on our computer, Like doc documents that are formatted and are non-plain text files, you need to use a byte stream to read them.

The classes that process these input and output in Java are placed in the java.io package, all input classes are subclasses of the byte input class (InputStream) and the character input class (Reader), and all output classes are subclasses of the byte output Class (OutputStream) and the character output class (Writer).

The main points we need to master are the following 16 categories:

File read-write throttle character stream

FileInputStream

FileOutputStream

FileReader

FileWriter

Read-write throttle character stream with cache

BufferedReader

BufferedWriter

Bufferedinputstream

Bufferedoutputstream

Byte stream character stream dedicated to data processing

DataInputStream

DataOutputStream

Reads the byte stream character stream of an object

ObjectInputStream

ObjectOutputStream

Conversion Stream (Byte stream converted to character streams)

InputStreamReader

OutputStreamWriter

PrintWriter

PrintStream (standard output stream, default output to console)

Java input and output streams are mainly Inputstream,outputstream, reader and writer four categories, the following two graphs to understand the subclass of the four class inheritance relationship.

Next look at the basic reading method of the InputStream class. Look at the following code:

Import java.io.*;
PublicClassfileinputstreamtest01{
PublicStaticvoidMainString[] (args) {
FileInputStream fis=Null
try{
To read a file, first create an input stream for the file
File path
String filepath="Abc.txt";Absolute path
String filepath= "F:\\bianchenglianxi\\java\\abc.txt"; Relative path
fis=NewFileInputStream (filepath);
Read file
IntI1=fis.read ();
IntI2=fis.read ();
IntI3=fis.read ();
IntI4=fis.read ();
IntI5=fis.read ();
IntI6=fis.read ();
IntI7=fis.read ();
System. out.println (I1);
   system. out.println (I2);
   system. out.println (i3);
   system. out.println (I4);
   system. out.println (i5);
   system. out.println (I6);
   system. out.println (i7);
   } catch (FileNotFoundException e) {
     e.printstacktrace ();
   s}
    catch (IOException e) {
     e.printstacktrace ();
   } finally{
      if (fis!= null) {
        try{
         fis.close ();
       } catch (IOException e) {
         e.printstacktrace ();
       }
     }
   }
 }
/span>

After compiling the run-time output:

/*
97
98
99
100
101
102
103
*/

1. Import the package java.io.* first;

2. To read a file, first create an input stream for the file, i.e. FileInputStream fis=new FileInputStream (filepath); Where filepath is the path to the file to be read in, either an absolute path or a relative path.

3. Use the Read () method to read the file.

4. When handling exceptions, be aware that the range of IOException is larger than the range of FileNotFoundException, so the former should be written in the back, or directly catch IOException.

5. Finally close the file using the close () method.

The above is the basic way to read the file. Look at the second program and throw an exception directly using throws.

Importjava.io.*;
Public class  fileinputstreamtest02{
  public< Span class= "Apple-converted-space" >&NBSP; static&NBSP; Void&NBSP; main (string[] args)   throws exception{
   fileinputstream fis= new< Span class= "Apple-converted-space" > fileinputstream ( "Abc.txt");
    while ( true) {
      int  Temp=fis.read ();
      if (temp==- 1) break;
    &NBSP;SYSTEM.OUT.PRINTLN (temp);
  &NBSP;}
   fis.read ();
 }
} /span>

The above program uses the while loop to read the file because it is a byte-by-byte read, so there are drawbacks, frequent access to the disk, damage to the disk, and inefficient access. Next look at the method of using the array to read the file, see the following code:

Import java.io.*;
PublicClassfileinputstreamtest03{
PublicStaticvoidMainString[] args) throws exception{
FileInputStream fis=NewFileInputStream ("Abc.txt");
Byte[] Bytes=Newbyte[3];Read up to three bytes per time
int read (byte[] bytes); The value of the int type returned by the method represents how many bytes were read this time
IntI1=fis.read (bytes);
Convert an bytes array to a string
System.Out.println (new String (bytes)); //ABC
int i2=fis.read (bytes);
System.  out.println (new String (bytes)); //def
int i3=fis.read (bytes);
System.  out.println (new String (bytes,0,i3)); //GEF
System.  out.println (I1); //3
System.  out.println (I2); //3
System.  out.println (i3); //1

Fis.close ();
}
}

After compiling the run-time output:

/*
abc
def
g
3
3
1
*/

1. The array read method is int read (byte[] bytes), which is read before an array is prepared in memory, with each read of multiple bytes stored in a byte array.

2.byte[] Bytes=new byte[3]; Sets the size of the array to read up to three bytes at a time.

3.int i1=fis.read (bytes); System.out.println (New String (bytes)); After the contents of the file are read into the array in bytes, the bytes array is converted to a string.

Finally upgrade, look at the loop read the contents of the file, the code is as follows:

/*
Loop read
*/
Importjava.io.*;
PublicClassfileinputstreamtest04{
Public static&NBSP; void  main (string[] args) throws exception{
    FileInputStream fis= new fileinputstream ( "Abc.txt");
    byte[] bytes= new&NBSP; byte[ 1024x768];
    while ( true) {
      int  Temp=fis.read (bytes);
      if (temp==- 1) break;
     system.out.print ( new string (bytes, 0, temp));
  &NBSP;}
   fis.close ();
 }
} /span>

After compiling the run-time output:

//abcdefg

Java I/O

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.