Dark Horse programmer-java basic learning IO stream 1

Source: Internet
Author: User

 
1. IO (Input Output) stream
1) IO streams are used to process data transmission between devices.
2) java operates data through a stream.
3) java and the objects used for stream operations are all in the IO package
4) streams are divided into two types by operation data: byte streams and byte streams.

 

 

I/O streams often use base classes
1) abstract base classes of byte streams: InputStream and OutputStream
2) abstract base class of the livestream: Reader and Writer
Note: The subclass names derived from these four classes are based on their parent classes.
Suffix of the subclass name.

 

 

Since IO streams are used to manipulate data,
The most common form of data is file.
Example
Requirement: create a file on the hard disk and write some text data.
*/
Import java. io .*;
Class FileWriterDemo
{
Public static void main (String [] args) throws IOException
{
// Create a FileWriter object. When the object is initialized, you must specify the file to be operated.
// And the file will be created under the specified directory. If a file with the same name already exists in the directory, it will be overwritten.
// In fact, this step defines the destination of the data to be stored.
FileWriter fw = new FileWriter ("demo.txt ");


// Call the write method to write the string to the stream.
Fw. write ("abcde ");


// Refresh the buffered data in the stream object.
// Fl data to the destination.
// Fw. flush ();


// Close the stream resource, but the data in the internal buffer will be refreshed once before it is disabled.
// Fl data to the destination.
// What is the difference between flush and flush: After flush is refreshed, the stream can continue to be used. After the flush is refreshed, the stream is closed.
Fw. close ();
}
}

 

 

 

. IO stream (IO Exception Handling Method)
1. IOException occurs when the underlying resource is called if it can be associated with the data on the device.
2. If "K: \ demo.txt" does not have K disks, A FileNotFoundException will be thrown (the system cannot find the specified path.
FileNotFoundException is a subclass of IOException.
3. If an exception is thrown during initialization, the initialization fails and the fw is empty, so the close () method of the object cannot be called,
Therefore, an NullPointerException is thrown. finally must judge whether the stream object to be closed is not equal to null.


Example:

/*
IO exception handling method.
*/
Import java. io .*;


Class FileWriterDemo2
{
Public static void main (String [] args)
{
FileWriter fw = null; // create external reference
Try
{
/* If you write FileWriter fw = new FileWriter ("demo.txt") inside try ");
Instead of writing FileWriter fw = null externally;
Write fw = new FileWriter ("demo.txt") internally ");
The function of the fw variable is only a try statement block.
*/
Fw = new FileWriter ("demo.txt"); // internal Initialization
Fw. write ("abcdefg ");


}
Catch (IOException e)
{
System. out. println ("catch:" + e. toString ());
}
Finally
{
Try
{
If (fw! = Null)
Fw. close (); // This statement also produces exceptions, so try again.
}
Catch (IOException e)
{
System. out. println (e. toString ());
}

}


}
}

 

 

IO stream (Continued file writing)
1. Add an overloaded constructor to FileWriter:
Public FileWriter (String fileName, boolean append) throws IOException
Construct a FileWriter object based on the given file name and boolean value indicating whether to append the written data.
Parameters:
FileName-a string that indicates the system-related file name.
Append-A boolean value. If it is true, data is written to the end of the file, rather than the start of the file.

 

/*
This example shows how to continue writing data to an existing file.
*/
Import java. io .*;
Class FileWriterDemo3
{
Public static void main (String [] args) throws IOException
{


// Pass a true parameter, indicating that the existing file is not overwritten. Data is continued at the end of an existing file.
FileWriter fw = new FileWriter ("demo.txt", true );


Fw. write ("nihao \ r \ nxiexie"); // "\ r \ n" in volume e Indicates a line feed.


Fw. close ();
}
}

 

 

IO stream (Text File Reading method 1)

Reader ---> FileReader (in java. io package)
1. Reader class
The abstract class used to read the livestream. The sub-classes must implement only read (char [], int, int) and close () methods ().
However, most subclasses will override some of the methods defined here to provide higher efficiency and/or other functions.
1) constructor:
Protected Reader () // protected indicates that only child classes can be used.
Create a new producer stream reader. Its important part will be synchronized with its own reader.
2) Special Methods:
(1) abstract void close ()
Close the stream and release all associated resources.

(2) int read ()
Public int read () throws IOException
Read a single character. Before the character is available, an I/O error occurs, or the stream is reached,
This method is always blocked. This method should be rewritten for subclasses that support efficient single-character input.


Return Value:
The characters read as integers in the range of 0 to 65535 (0x00-0xffff ),
If the stream has reached the end,-1 is returned.
 
(3) int read (char [] cbuf)
Read characters into the array.


2. FileReader class
1) public class FileReader extends InputStreamReader
A convenient class for reading character files. This constructor assumes that the default character encoding and the default byte buffer size are both appropriate.
To specify these values, you can first construct an InputStreamReader on FileInputStream.


FileReader is used to read the shard stream. To read the original byte stream, consider using FileInputStream.
2) constructor:
Public FileReader (File file) throws FileNotFoundException
Create a new FileReader when the File from which the data is read is specified.


/*
Method 1: Read a character and print a character
*/
Import java. io .*;


Class FileReaderDemo
{
Public static void main (String [] args) throws IOException
{
/* Create a file to read the stream object and associate it with the file with the specified name.
Ensure that the file already exists. If the file does not exist, an exception occurs. FileNotFoundException */
FileReader fr = new FileReader ("demo.txt ");


// Call the read method of the stream object.
// Read (): one character is read at a time. And it will read down automatically.

Int ch = 0;


While (ch = fr. read ())! =-1) // The ending sign is-1;
{
System. out. println (
}
Fr. close ();
}
}

 

 

Method 2: Read through character array.
1. read (char [] chs) Method
Public int read (char [] cbuf)
Throws IOException reads characters into arrays. This method is always blocked until an input is available, an I/O error occurs, or the end of the stream has been reached.


Parameters:
Cbuf-Target Buffer Zone
Return Value:
Number of characters read. If the number of characters reaches the end of the stream,-1 is returned.
Throw:
IOException-if an I/O error occurs
/*
Method 2: Read through character array.
*/


Import java. io .*;


Class FileReaderDemo2
{
Public static void main (String [] args) throws IOException
{
FileReader fr = new FileReader ("demo.txt ");

 

// Define an array of characters. Used to store read characters.
// The read (char []) returns the number of characters read.
Char [] buf = new char [1024];


Int num = 0;
While (num = fr. read (buf ))! =-1)
{
System. out. println (new String (buf, 0, num ));
}

 

Fr. close ();
}
}

 

 

 

 


 

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.