Article From:https://www.cnblogs.com/pengpeng1208/p/9969458.html

  Java Stream, File and IO

  Java.ioPackages contain almost all the classes needed for input and output operations. All these stream classes represent input sources and output targets.

  Java.ioThe streams in packages 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 a source and the output stream represents writing data to a target.

  JavaIt provides powerful and flexible support for I/O, and makes it more widely used in file transfer and network programming.

  But this section describes the most basic I/O-related functions of harmony and flow. We will learn about these functions through an example.

  Read console input

  JavaThe console input is completed by Sysem. in.

  To get a character stream bound to the console, you can create a character stream by wrapping System. in in a BufferedReader object.

  The following is the basic syntax for creating BufferedReader:

  BufferedReader br = new BufferedReader(new

  InputStreamReader(System.in));

  BufferedReaderAfter the object is created, we 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 console

  To read a character from a BufferedReader object, the read () method is used. Its grammar is as follows:

  int read( ) throws IOException

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

  The following program demonstrates the use of read () to read characters from the console until the user enters “q”.

  // Use BufferedReader to read characters in the console

  import java.io.*;

  public class BRRead {

  public static void main(String args[]) throws IOException

  {

  char c;

  // Create BufferedReader with System.in

  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’);

  }

  }

  The results of compiling and running the above examples are as follows:

  Enter characters, ‘q’ to quit.

  123abcq

  1

  2

  3

  a

  b

  c

  q

  Read strings from console

  Reading a string from standard input requires using BufferedReader’s readLine () method.

  Its 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 characters in the console

  import java.io.*;

  public class BRReadLines {

  public static void main(String args[]) throws IOException

  {

  // Create BufferedReader with System.in

  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 results of compiling and running the above examples are as follows:

  Enter lines of text.

  Enter ‘end’ to quit.

  This is line one

  This is line one

  This is line two

  This is line two

  end

  end

  console output

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

  PrintStream The OutputStream class is inherited and the method write () is implemented. In this way, write () can also be used to write operations to the console.

  PrintStream The simplest format for defining write () is as follows:

  void write(int byteval)

  This method writes the low octet bytes of byteval into the stream.

  Example

  The following example uses write () to output the character “A” and the following newline characters to the screen:

  import java.io.*;

  // Demonstrate 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 example to output the “A” character in the output window

  A

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

  Read and write files

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

  The following diagram is a class hierarchy diagram describing the input and output flows.

  The two important streams to be discussed below are FileInputStream and FileOutputStream:

  FileInputStream

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

  There are many constructors that can be used to create objects.

  You can use the file name of the 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 need to create a file object using the File () method:

  File f = new File(“C:/java/hello”);

  InputStream f = new FileInputStream(f);

  When you create an InputStream object, you can read the stream or perform other flow operations using the following methods.

  Sequence Number Method and Description

  1public void close() throws IOException{}

  Close the file input stream and release all system resources associated with the stream. Throw an IOException exception.

  2protected 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. Throw an IOException exception.

  3public 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, and – 1 if it has reached the end.

  4public int read(byte[] r) throws IOException{}

  This method reads R. length bytes from the input stream. Returns the number of bytes read. Returns – 1 if it is at the end of the file.

  5public int available() throws IOException{}

  Returns the number of bytes that the next method that calls this input stream can read from this input stream without blocking. Returns an integer value.

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

  ByteArrayInputStream

  DataInputStream

  FileOutputStream

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

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

  There are two constructors that can be used to create FileOutputStream objects.

  Create an output stream object using a file name of a 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 need to create a file object using the File () method:

  File f = new File(“C:/java/hello”);

  OutputStream f = new FileOutputStream(f);

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

  Sequence Number Method and Description

  1public void close() throws IOException{}

  Close the file input stream and release all system resources associated with the stream. Throw an IOException exception.

  2protected 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. Throw an IOException exception.

  3public void write(int w)throws IOException{}

  This method writes the specified bytes to the output stream.

  4public void write(byte[] w)

  Write bytes of W. length length in the specified array to OutputStream.

  In addition to Output Stream, there are other output streams. For more details, refer to the following links:

  ByteArrayOutputStream

  DataOutputStream

  Example

  Here’s an example of how InputStream and OutputStream are used:

  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 above program first creates the file test. txt, and writes the given number into the file in binary form, and outputs it to the console.

  Because the above code is written in binary, there may be scrambling. You can use the following code examples to solve the scrambling problem:

  //File name: fileStreamTest2. Java

  import 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 FileOutputStream objects. Files that do not exist are automatically created

  OutputStreamWriter writer = new OutputStreamWriter(fop, “UTF-8”);

  // Build OutputStreamWriter object, parameters can specify the encoding, default is the operating system default encoding, windows is GBK

  writer.append(“Chinese input “;

  // Write to Buffer

  writer.append(“\r\n”);

  //Line feed

  writer.append(“English”);

  // Refresh the cache flush and write to the file. If there is no writing below, direct close will also write to the file.

  writer.close();

  //Close the write stream and write the contents of the buffer to the file, so the comments above are omitted.

  fop.close();

  // Close the Output Stream and Release System Resources

  FileInputStream fip = new FileInputStream(f);

  // Building FileInputStream objects

  InputStreamReader reader = new InputStreamReader(fip, “UTF-8”);

  // Construct the InputStreamReader object with the same encoding as writing

  StringBuffer sb = new StringBuffer();

  while (reader.ready()) {

  sb.append((char) reader.read());

  // Convert to char and add to StringBuffer object

  }

  System.out.println(sb.toString());

  reader.close();

  // Close the read stream

  fip.close();

  // Close the input stream and release system resources

  }

  }

  Documents and I/O

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

  File Class(Class)

  FileReader Class(Class)

  FileWriter Class(Class)

  JavaDirectory in

  Create a directory:

  FileThere are two methods in the class to create folders:

  mkdir( )Method creates a folder, returns true for success and false for failure. 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 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);

  // 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 separators by convention in UNIX and Windows. If you use a separator (/) in 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, calling the isDirectory () method returns true.

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

  The following example shows how to use the list () method to check the contents of 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 compiling and running the above examples are 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

  (Editor: Lei Linpeng Source: Network)

Link of this Article: Java Stream, File and IO

Leave a Reply

Your email address will not be published. Required fields are marked *