Java Stream (stream), file, and IO

Source: Internet
Author: User

Introduction to Java stream, file, and IO

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.

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:

In the java.io package to manipulate the contents of the main two major categories: byte stream, character stream, two categories are divided into input and output operations.

The output data in the byte stream is mainly used OutputStream to complete, the input is made InputStream ; the output in the character flow is mainly done using the Writer class, and the input stream is mainly used by the Reader class. These four are abstract classes.

A package dedicated to the input-output functionality is available in Java java.io , including:

    • InputStream, OutputStream , Reader , Writer .
    • InputStreamAnd OutputStream , the two are designed for byte streams and are primarily used to process bytes or binary objects.
    • ReaderAnd Writer , the two are designed for character streams (1 characters in 2 bytes) and are primarily used to handle characters or strings.

The common System.in is actually InputStream object.

Byte stream converted to character stream

Console input system.in Create BufferedReader create character turns

        

Reading from the console
BufferedReader br=new BufferedReader (New InputStreamReader (system.in));//read from File
BufferedReader br=new BufferedReader (New InputStreamReader (New FileInputStream ("D:/text.txt"));

For a simple description of the three classes in the example above:

    • InputStream: is a superclass of all byte input streams, which generally uses its subclasses: and FileInputStream so on, it can output byte stream;
    • InputStreamReader: It is a bridge between byte stream and character stream, can output character stream as character stream, and can specify character set for byte stream, and can output characters.
    • BufferedReader: Provides a common buffered text read, readLine() reads a line of text, reads text from the character input stream, buffers individual characters, and provides efficient reading of characters, arrays, and rows.

 

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:

InputStream F = new fileinputstream("c:/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:

file f = new file("c:/java/hello"); InputStream out = new FileInputStream(f);

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

Serial Number method and Description
1 public void Close () throws ioexception{}
Closes this file input stream and frees all system resources related to this stream. Throws a IOException exception.
2 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.
3 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.
4 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.
5 public int available () throws ioexception{}
Returns the number of bytes that the next method invoked on this input stream can be read from this input stream without blocking. 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:

OutputStream F = new fileoutputstream("c:/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:

file f = new file("c:/java/hello"); OutputStream F = 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.

Serial Number method and Description
1 public void Close () throws ioexception{}
Closes this file input stream and frees all system resources related to this stream. Throws a IOException exception.
2 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.
3 public void Write (int w) throws ioexception{}
This method writes the specified bytes to the output stream.
4 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

Directories in Java

To create a directory:

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.

The following example creates the "/tmp/user/java/bin" folder:

Createdir.java File Code:
Import Java.io.File; public class Createdir {public  static void main (string args[]) {    string dirname = "/tmp/user/java/bin";    File D = new file (dirname);    Now create the Directory    d.mkdirs ();  }}

Compile and execute the above code to create the directory "/tmp/user/java/bin".

Note: Java automatically distinguishes file path delimiters by convention in UNIX and Windows. If you use the delimiter (/) in the Windows version of Java, the path can still be parsed correctly.

Read Directory

A directory is actually a file object that contains other files and folders.

If you create a File object and it is a directory, then calling the Isdirectory () method returns True.

You can extract a list of the files and folders it contains by calling the list () method on the object.

The example shown below shows how to use the list () method to check what is contained in a folder:

Dirlist.java File Code:
Import Java.io.File; public class Dirlist {public  static void main (string args[]) {    string dirname = "/tmp";    File F1 = new file (dirname);    if (F1.isdirectory ()) {      System.out.println ("directory" + dirname);      String s[] = F1.list ();      for (int i=0; i < s.length; i++) {        file F = new File (dirname + "/" + s[i]);        if (F.isdirectory ()) {          System.out.println (S[i] + "is a directory"), or        else {          System.out.println (S[i] + "is a file"); c12/>}}}    else {      System.out.println (dirname + "not a Directory");  }}}

The results of the above example compilation run as follows:

Directory/is a directory is a directory is a directory      test.  is a file that is a file index.  is a file is a directory           

Delete a directory or file

You can use the java.io.File.delete () method to delete files.

The following code removes the directory/tmp/java/, even if the directory is not empty.

To test the directory structure:

/tmp/java/|--1.log|-- test     

Deletefiledemo.java File Code:
Import Java.io.File; public class Deletefiledemo {public  static void Main (String args[]) {      //here is modified to its own test directory    file folder = new file ( "/tmp/java/");    DeleteFolder (folder);  }   Delete file and directory public  static void DeleteFolder (file folder) {    file[] files = folder.listfiles ();        if (files!=null) {for             (File f:files) {                if (f.isdirectory ()) {                    deletefolder (f);                } else {                    F.delete ();        }}} Folder.Delete ();    }

Java Stream (stream), file, and IO

Related Article

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.