Java Stream (stream), file, and IO

Source: Internet
Author: User

The java.io package contains almost all the required classes for operation input and output. All of these flow classes represent the input source and output destination.

The streams in the Java.io package support many formats, such as basic types, objects, localized character sets, and so on.

A stream can be understood as a sequence of data. The input stream represents reading data from one source, and the output stream represents writing data to a target.

Java provides powerful and flexible support for I/O, making it more widely available in file transfer and network programming.

However, this section describes the most basic and current-to-I/O-related features. We will learn these features through an example.

Read console input

Java console input is completed by system.in.

To get a character stream bound to the console, you can wrap the system.in in a BufferedReader object to create a character stream.

Here is the basic syntax for creating BufferedReader:

 package   Object.inputsystem;  import   Java.io.BufferedReader;  import   java.io.IOException;  import   Java.io.InputStreamReader;  public  class   systemin { public  static  void  main (string[] args)   Throws   IOException {BufferedReader BufferedReader  = new  bufferedreader (new      InputStreamReader (system.in)); }}

Once the BufferedReader object is created, we can use the read () method to read a character from the console or to read a string with the ReadLine () method.

Read multi-character input from the console

To read a character from a BufferedReader object to use the Read () method, its syntax is as follows:

int throws IOException

Each time the read () method is called, it reads a character from the input stream and returns the character as an integer value. Returns-1 when the stream ends. The method throws IOException.

Class:tt

 PackageObject.inputsystem;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader; Public classSystemin { Public Static voidMain (string[] args)throwsIOException {BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (system.in)); intRead =Bufferedreader.read ();    SYSTEM.OUT.PRINTLN (read); }}

Console:

A65

Class:brread

 PackageObject.inputsystem;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader; Public classBrread { Public Static voidMain (string[] args)throwsIOException {BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (system.in)); intc =-1;  while((c = Bufferedreader.read ())! = 1) {System.out.println (Char) c); if((Char) c = = ' Q ')                 Break; }    }}

Console:

Limelimeqq
Reading a string from the console

Reading a string from standard input requires the use of the BufferedReader ReadLine () method.

Its general format is:

throws IOException

Class:tt

 PackageObject.inputsystem;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader; Public classSystemin { Public Static voidMain (string[] args)throwsIOException {BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (system.in)); String Read=Bufferedreader.readline ();    SYSTEM.OUT.PRINTLN (read); }}

Console:

Abcdabcd

Class:brreadlines

 PackageObject.inputsystem;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader; Public classBrreadlines { Public Static voidMain (string[] args)throwsIOException {BufferedReader BufferedReader=NewBufferedReader (NewInputStreamReader (system.in)); String ReadLine= "";  while(! (ReadLine = Bufferedreader.readline ()). Equals ("End") {System.out.println (readLine); }    }}

Console:

Limelimeoracleoracleend

Version after JDK 5 We can also use the Java Scanner class to get input from the console.

Console output

As already described earlier, the output of the console is done by print () and println (). These methods are defined by the class PrintStream, and System.out is a reference to the class object.

PrintStream inherits the OutputStream class and implements the method write (). In this way, write () can also be used for writing to the console.

The simplest format for the printstream definition of write () is as follows:

void Write (int byteval)

This method writes the low eight-bit bytes of the byteval to the stream.

Class:writedemo

 PackageObject.outputsystem; Public classWritedemo { Public Static voidMain (string[] args) {//A = B0100 0001        intb = ' A ';        System.out.write (b); System.out.write (' \ n '); //0x41 = B0100 0001        byteBT = (byte) 0x41;        System.out.write (BT); System.out.write (' \ n '); //321 = B0001 0100 0001        intBigger = 321;        System.out.write (bigger); System.out.write (' \ n '); }}

Console:

Aaa

Note:the Write () method is not used frequently because the print () and println () methods are more convenient to use.

Read and write files

As mentioned earlier, a stream is defined as a data series. The input stream is used to read data from the source, and the output stream is used to write data to the target.

is a class-level diagram that describes the input stream and the output stream.

Txt:

Object     : InputStream         : FileInputStream    : OutputStream        : FileOutputStream-----------------  -------------------------------            : bytearrayinputstream    : Bytearrayoutputstream---------- --------------------------------------        : filterinputstream        : Bufferedinputstream        :D Atai Nputstream        :P ushbackinputstream    : Filteroutputstream        : Bufferedoutputstream        :D Ataoutputstream        :P rintstream    ------------------------------------------------
    :stringbufferinputstream    : Sequenceinputstream

Two important streams are FileInputStream and FileOutputStream:

FileInputStream

The stream is used to read data from a file, and its objects can be created with the keyword new.

There are several construction methods that you can use to create objects.

You can use the file name of a string type to create an input stream object to read the file:

New FileInputStream ("F:/java/hello");

You can also use a file object to create an input stream object to read the file. We first have to use the file () method to create a Document object:

New File ("F:/java/hello"new FileInputStream (F);

When you create a InputStream object, you can use the following methods to read the stream or perform other flow operations.

⊙ public Void Close () throws ioexception{}: closes this file input stream and frees all system resources related to this stream. Throws a IOException exception.

⊙ protected void Finalize () throws IOException {}: This method clears the connection to the file. Make sure that the Close method is called when the file input stream is no longer referenced. Throws a IOException exception.

⊙ public int read (int r) throws ioexception{}: This method reads the specified byte of data from the InputStream object. Returns an integer value. Returns the next byte of data, or 1 if it has reached the end.

⊙ public int Read (byte[] r) throws ioexception{}: This method reads bytes of r.length length from the input stream. Returns the number of bytes read. Returns 1 if it is the end of the file.

⊙ public int available () throws ioexception{}: Returns the number of bytes that the next method that is called on this input stream can be read from this input stream in a nonblocking manner. Returns an integer value.

In addition to InputStream, there are some other input streams, more details refer to the following links:

    • Bytearrayinputstream
    • DataInputStream
FileOutputStream

This class is used to create a file and write data to the file.

If the stream does not exist before the file is opened for output, the stream creates the file.

There are two construction methods that you can use to create a FileOutputStream object.

Create an output stream object using the file name of the string type:

New FileOutputStream ("F:/java/hello")

You can also use a file object to create an output stream to write a file. We first have to use the file () method to create a Document object:

New File ("F:/java/hello"new FileOutputStream (F);

Once the OutputStream object is created, you can use the following methods to write to the stream or perform other flow operations.

⊙ public Void Close () throws ioexception{}: closes this file input stream and frees all system resources related to this stream. Throws a IOException exception.

⊙ protected void Finalize () throws IOException {}: This method clears the connection to the file. Make sure that the Close method is called when the file input stream is no longer referenced. Throws a IOException exception.

⊙ protected void Finalize () throws IOException {}: This method clears the connection to the file. Make sure that the Close method is called when the file input stream is no longer referenced. Throws a IOException exception.

⊙ public Void Write (byte[] W): writes bytes of w.length length in the specified array to outputstream.

In addition to the outputstream, there are some other output streams, more details refer to the following links:

    • Bytearrayoutputstream
    • DataOutputStream

Class:filestreamtest

 Packageobject. Stream;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException; Public classFilestreamtest { Public Static voidMain (string[] args)throwsIOException {byte[] Bwrite = {11, 21, 3, 40, 5 }; FileOutputStream FileOutputStream=NewFileOutputStream ("Tt.txt");  for(inti = 0;i < bwrite.length;i++) {fileoutputstream.write (bwrite[i]);                } fileoutputstream.close (); // -- -- -- -- -- -- -- -- --FileInputStream FileInputStream =NewFileInputStream ("Tt.txt"); intAvailable =fileinputstream.available ();  for(inti = 0;i < available;i++) {System.out.print (Char) Fileinputstream.read () + "");    } fileinputstream.close (); }}

Console:

Result:

The above code is written by the binary, there may be garbled, you can use the following code example to solve the garbled problem:

Class:filestreamreaderwriter

 Packageobject. Stream;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter; Public classFilestreamreaderwriter { Public Static voidMain (string[] args)throwsIOException {fileoutputstream FileOutputStream=NewFileOutputStream ("Tt.txt"); //Build the OutputStreamWriter object, parameters can specify the encoding, default is the operating system default encoding, Windows is GBKOutputStreamWriter OutputStreamWriter =NewOutputStreamWriter (FileOutputStream, "UTF-8"); //Write to BufferOutputstreamwriter.append ("Chinese Input:"). Append ("\ r \ n")). Append ("It's like a parade and a show, you just touch my side, you're obsessed with the look, you know I'm actually that side, you know me, you know me? \ n"). Append ("lime").); //Flush Cache Punch, write to file, if no content is written below, direct close also writesOutputstreamwriter.flush (); Outputstreamwriter.append ("Can You blow my whistle baby, whistle baby?"); //The write stream is closed and the buffer contents are written to the file, so flush above can be commented outOutputstreamwriter.close (); //turn off the output stream and release system resourcesFileoutputstream.close (); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- --FileInputStream FileInputStream =NewFileInputStream ("Tt.txt");//build the InputStreamReader object with the same encoding as the writeInputStreamReader InputStreamReader =NewInputStreamReader (FileInputStream, "UTF-8"); StringBuffer StringBuffer=NewStringBuffer ();//Ready is a non-blocking method to see if the stream is prepared to be read, so it returns immediately.          while(!Inputstreamreader.ready ()) {System.out.println ("Not Ready"); }         while(Inputstreamreader.ready ()) {Stringbuffer.append (Char) Inputstreamreader.read ());        } System.out.println (Stringbuffer.tostring ());        Fileinputstream.close ();    Inputstreamreader.close (); }}
File and I/O

There are also classes about files and I/O, and we need to know:

    • File Class (Class)
    • FileReader Class (Class)
    • FileWriter Class (Class)
Directory creation directory in Java:

There are two methods in the file class that can be used to create a folder:

    • The mkdir () method creates a folder, returns True if successful, and returns False if it fails. Failure indicates that the path specified by the file object already exists, or that the folder cannot be created because the entire path does not yet exist.
    • The mkdirs () method creates a folder and all its parent folders.

La La la

La La la

La La la

La La la

La La la

La La la

Java Stream (stream), file, and IO

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.