Java Stream, File, IO, streamio

Source: Internet
Author: User

Java Stream, File, IO, streamio

The Java. io package contains almost all input and output classes. All these stream classes represent the Input Source and output target.

The stream in the Java. io package supports many formats, such as basic types, objects, and localized character sets.

A stream can be understood as a sequence of data. The input stream reads data from a source, and the output stream writes data to a target.

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

However, this section describes the most basic functions related to stream and I/O. We will use examples to learn these functions.

Read console input

The Java console input is completed by Sysem. in.

To obtain a consumer stream bound to the console, you can wrap System. in A BufferedReader object to create a consumer stream.

The basic syntax for creating BufferedReader is as follows:

BufferedReader br = new BufferedReader(new                       InputStreamReader(System.in));

After the BufferedReader object is created, you can use the read () method to read a character from the console or the readLine () method to read a string.

Read multi-character input from the console

The read () method is used to read a character from the BufferedReader object. Its syntax is as follows:

int read( ) throws IOException

Each time you call the read () method, it reads a character from the input stream and returns this character as an integer. -1 is returned when the stream ends. This method throws an IOException.

The following program demonstrates that the read () method is used to continuously read characters from the console until the user enters "q ".

// Use BufferedReader to read the character import java on the console. io. *; public class BRRead {public static void main (String args []) throws IOException {char c; // use System. in to create BufferedReader br = new BufferedReader (new InputStreamReader (System. in); System. out. println ("Enter characters, 'q' to quit. "); // read the character do {c = (char) br. read (); System. out. println (c);} while (c! = 'Q ');}}

 

The above example compilation and running results are as follows:

Enter characters, 'q' to quit.123abcq123abcq
Read strings from the console

To read a string from a standard input, use the readLine () method of BufferedReader.

The general format is:

String readLine( ) throws IOException

The following program reads and displays character lines until you enter the word "end ".

// Use BufferedReader to read the character import java on the console. io. *; public class BRReadLines {public static void main (String args []) throws IOException {// use System. in to create BufferedReader br = new BufferedReader (new InputStreamReader (System. in); String str; System. out. println ("Enter lines of text. "); System. out. println ("Enter 'end' to quit. "); do {str = br. readLine (); System. out. println (str);} while (! Str. equals ("end "));}}

 

The above example compilation and running results are as follows:

Enter lines of text.Enter 'end' to quit.This is line oneThis is line oneThis is line twoThis is line twoendend
Console output

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

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

PrintStream defines the simplest format of write () as follows:

void write(int byteval)

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

Instance

The following example uses write () to output the character "A" and the followed line break to the screen:

Import java. io. *; // demo System. out. write (). public class WriteDemo {public static void main (String args []) {int B; B = 'a'; System. out. write (B); System. out. write ('\ n ');}}

 

Run the above instance and output the "A" character in the output window.

A

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

Read/write files

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

It is a class hierarchy diagram that describes the input stream and output stream.

The following two important streams will be discussed: FileInputStream and FileOutputStream:

FileInputStream

This stream is used to read data from a file. Its object can be created with the keyword "new.

Multiple constructor methods can be used to create objects.

You can use a string file name 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 files. First, we must use the File () method to create a File object:

File f = new File("C:/java/hello");InputStream f = new FileInputStream(f);

After an InputStream object is created, you can use the following method to read the stream or perform other stream operations.

Serial number Method and description
1 Public void close () throws IOException {}
Close the input stream of this file and release all system resources related to this stream. An IOException is thrown.
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. An IOException is thrown.
3 Public int read (int r) throws IOException {}
This method reads data of the specified byte from the InputStream object. Returns an integer. Returns the next byte of data. If it has reached the end,-1 is returned.
4 Public int read (byte [] r) throws IOException {}
This method reads the length of the r. length byte from the input stream. Returns the number of bytes read. -1 is returned if it is the end of the file.
5 Public int available () throws IOException {}
Returns the number of bytes that can be read from the input stream without blocking the method called next time. Returns an integer.

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

  • ByteArrayInputStream
  • DataInputStream
FileOutputStream

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

If the target file does not exist before the stream opens the file for output, the stream creates the file.

You can use two constructor methods to create a FileOutputStream object.

Use a string file name to create an output stream object:

OutputStream f = new FileOutputStream("C:/java/hello") 

You can also use a file object to create an output stream to write files. First, we must use the File () method to create a File object:

File f = new File("C:/java/hello");OutputStream f = new FileOutputStream(f);

After the OutputStream object is created, you can use the following method to write streams or perform other stream operations.

Serial number Method and description
1 Public void close () throws IOException {}
Close the input stream of this file and release all system resources related to this stream. An IOException is thrown.
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. An IOException is thrown.
3 Public void write (int w) throws IOException {}
This method writes the specified byte to the output stream.
4 Public void write (byte [] w)
Write the w. length bytes in the specified array to OutputStream.

In addition to OutputStream, there are some other output streams. For more details, refer to the following link:

  • ByteArrayOutputStream
  • DataOutputStream
Instance

The following is an example of InputStream and OutputStream usage:

import java.io.*;public class fileStreamTest{   public static void main(String args[]){      try{      byte bWrite [] = {11,21,3,40,5};      OutputStream os = new FileOutputStream("test.txt");      for(int x=0; x < bWrite.length ; x++){         os.write( bWrite[x] ); // writes the bytes      }      os.close();           InputStream is = new FileInputStream("test.txt");      int size = is.available();      for(int i=0; i< size; i++){         System.out.print((char)is.read() + "  ");      }      is.close();   }catch(IOException e){      System.out.print("Exception");   }       }}

 

The program first creates the file test.txt, writes the given number into the file in binary format, and outputs it to the console.

The above code may be garbled because it is written in binary format. You can use the following code example to solve the garbled problem:

// File name: fileStreamTest2.javaimport java. io. *; public class fileStreamTest2 {public static void main (String [] args) throws IOException {File f = new File ("a.txt"); FileOutputStream fop = new FileOutputStream (f ); // construct the FileOutputStream object. If the object does not exist, the new OutputStreamWriter writer = new OutputStreamWriter (fop, "UTF-8") is automatically created; // construct the OutputStreamWriter object, the parameter can specify the encoding, the default value is the default Operating System encoding, and gbk writer on windows. append ("Chinese Input"); // write to the buffer writer. append ("\ r \ n"); // wrap writer. append ("English"); // refresh the cache and write it to the file. If no content is written below, directly close it and write it to writer. close (); // close the write stream, and write the buffer content to the file. close (); // close the output stream and release the system resource FileInputStream fip = new FileInputStream (f); // construct the FileInputStream object InputStreamReader reader = new InputStreamReader (fip, "UTF-8 "); // construct the InputStreamReader object. The encoding and writing are the same as StringBuffer sb = new StringBuffer (); while (reader. ready () {sb. append (char) reader. read (); // convert to char and add it to the StringBuffer object} System. out. println (sb. toString (); reader. close (); // close the read stream fip. close (); // close the input stream and release system resources }}

 

Files and I/O

We also need to know about the file and I/O classes:

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

There are two methods in the File class for creating folders:

  • Mkdir ()Method To create a folder. If the folder is successfully created, true is returned. If the folder fails, false is returned. Failure indicates that the specified path of the File object already exists, or the folder cannot be created because the entire path does not exist.
  • Mkdirs ()Method To create a folder and all its parent folders.

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

Import java. io. file; public class CreateDir {public static void main (String args []) {String dirname = "/tmp/user/java/bin"; File d = new File (dirname ); // 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 in UNIX and Windows according to conventions. If you use the separator (/) in Windows Java, the path can still be correctly parsed.

Read directory

A directory is actually a File object, which contains other files and folders.

If you create a File object and it is a directory, the isDirectory () method will return true.

You can call the list () method on this object to extract the list of files and folders it contains.

The following example shows how to use the list () method to check the content contained in a folder:

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 of " + 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");            } else {               System.out.println(s[i] + " is a file");            }         }      } else {         System.out.println(dirname + " is not a directory");    }  }}

 

The above example compilation and running results are as follows:

Directory of /tmpbin is a directorylib is a directorydemo is a directorytest.txt is a fileREADME is a fileindex.html is a fileinclude is a directory

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.