Java Stream (stream), file, and IO

Source: Internet
Author: User

Java Stream (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.


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:

BufferedReader br = 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 read a word with the ReadLine () method

Character string.


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 read () 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.


The following program demonstrates the use of the Read () method to continuously read characters from the console until the user enters "Q".

<span style= "FONT-SIZE:18PX;" >//use BufferedReader to read character import java.io.* in the console; public class Brread {public   static void Main (String args[]) throws IOException   {      char C;      Use system.in to create BufferedReader       bufferedreader br = new BufferedReader (new                          InputStreamReader (system.in));      System.out.println ("Enter characters, ' Q ' to quit.");      Read character do      {         c = (char) br.read ();         System.out.println (c);      } while (c! = ' q ');}   } </span>

The results of the above example compilation run as follows:

Enter characters, ' Q ' to quit.

123abcq

1

2

3

A

B

C

Q


reading a string from the console

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


Its general format is:

String ReadLine () throws IOException

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

<span style= "FONT-SIZE:18PX;" >//using BufferedReader to read characters in the console import java.io.*;p ublic class Brreadlines {public   static void Main (String args[]) th Rows IOException   {      //use system.in to create BufferedReader       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"));}   } </span>


The results of the above example compilation run as follows:
Enter lines of text.
Enter ' End ' to quit.
This was line one
This was line one
This was line
This was line
End
End

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 the class

A reference to the 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.


Instance

The following example uses write () to output the character "A" and the immediately 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 output "A" character in Output window

A

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.


The two important streams that will be discussed below 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:

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 f = new FileInputStream (f);

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

In addition to InputStream, there are some other input streams, with more details referencing the following classes:

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.


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

Bytearrayoutputstream

DataOutputStream


Instance


Here is an example demonstrating the usage of InputStream and OutputStream:

Import java.io.*; public class filestreamtest{public    static void Main (String args[]) {       try{      byte bwrite [] = {11,21,3,40,5};< C3/>outputstream OS = new FileOutputStream ("test.txt");      for (int x=0; x < bwrite.length; + +) {         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 above program first creates the file Test.txt and writes the given number in binary form into the file and outputs it to the console.


The above code is written by the binary, there may be garbled, 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);        Build FileOutputStream object, file does not exist will automatically new OutputStreamWriter writer = new OutputStreamWriter (FOP, "UTF-8");        Constructs the OutputStreamWriter object, the parameter can specify the encoding, defaults to the operating system default encoding, Windows is GBK writer.append ("Chinese input");        Write to buffer writer.append ("\ r \ n");        NewLine Writer.append ("中文版");        Flush cache Punch, write to file, if there is no content written below, direct close will also write Writer.close ();        The write stream is closed and the buffer contents are written to the file, so the comment above is fop.close ();        Turn off the output stream and release the system resources FileInputStream FIP = new FileInputStream (f);        Build FileInputStream object InputStreamReader reader = new InputStreamReader (FIP, "UTF-8");   Build InputStreamReader object, encode and write the same stringbuffer sb = new StringBuffer ();     while (Reader.ready ()) {sb.append (char) reader.read ());        Go to char and add to StringBuffer object} System.out.println (Sb.tostring ());        Reader.close ();        Turn off read stream fip.close (); Close the input stream and release the system resources}}

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)


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 because

The entire path does not yet exist and the folder cannot be created.

The Mkdirs () method creates 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);      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

The path can still be correctly parsed.

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:

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 results of the above example compilation run as follows:

Directory of/tmp
Bin is a directory
Lib is a directory
Demo is a directory
Test.txt is a file
README is a file
Index.html is a file
Include is a directory





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.