18, Java stream, file and IO of spring cloud distributed microservice Cloud Architecture for Java

Java stream, file, and IO    The Ja...
Read console input
Read multi character input from console
BRRead.java file code:
Read string from console
BRReadLines.java file code:
console output
WriteDemo.java file code:
Read write file
FileInputStream
FileOutputStream
fileStreamTest.java file code:
fileStreamTest2.java file code:
Directories in Java
CreateDir.java file code:
Read directory
DirList.java file code:
Delete directory or file
DeleteFileDemo.java file code:
Java stream, file, and IO   

The Java.io package contains almost all the classes required for operation input and output. All of these flow classes represent input sources and output destinations.

Streams in the Java.io package support many formats, such as basic types, objects, localized character sets, and so on. Recommended distributed architecture Source address

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.

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

However, this section covers the most basic flow and I/O related functions. We will learn these functions through examples.

Read console input

Java console input is done by System.in.

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

The following is the basic syntax for creating BufferedReader:

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

After the BufferedReader 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 the BufferedReader object, 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 that character as an integer value. Returns - 1 when the flow ends. This method throws an IOException.

The following program demonstrates using the read() method to continuously read characters from the console until the user enters them   q.

BRRead.java file code:

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

The compilation and operation results of the above examples are as follows:

Input character, Press 'q' Key exit. xxx r u n o o b q q

Read string from console

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

Its general format is:

String readLine( ) throws IOException

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

BRReadLines.java file code:

//Use BufferedReader to read characters on the console import java.io.*; public class BRReadLines { public static void main(String[] args) throws IOException { // Create BufferedReader using 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 compilation and operation results of 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

In the version after JDK 5, we can also use the Java Scanner class to obtain the console input.

console output

As mentioned earlier, the output of the console is completed 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 write to and from the console.

The simplest format of PrintStream definition write() is as follows:

void write(int byteval)

This method writes the lower octet of byteval to the stream.

example

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

WriteDemo.java file code:

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 the print() and println() methods are more convenient to use.

Read write file

As mentioned earlier, 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.

The following figure is a class hierarchy diagram describing input flow and output flow.

The two important flows to be discussed below are   FileInputStream   and   FileOutputStream.

FileInputStream

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

There are several construction methods for creating 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 the file. First, we have to use the File() method to create a file object:

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

After creating the InputStream object, you can use the following methods to read the stream or perform other stream operations.

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.

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

Create an output stream object using a string file name:

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

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

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

After creating the OutputStream object, you can use the following methods to write to the stream or perform other stream operations.

example

The following is an example that demonstrates the usage of InputStream and OutputStream:

fileStreamTest.java file code:

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, writes the given number into the file in binary form, and outputs it to the console at the same time.

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

fileStreamTest2.java file code:

//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); // Build a FileOutputStream object. If the file does not exist, it will be automatically created OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); // When building the OutputStreamWriter object, the parameters can specify the code. The default is the operating system default code, and gbk on windows writer.append("Chinese input"); // Write to buffer writer.append("\r\n"); // Line feed writer.append("English"); // Refresh the cache flush and write it to the file. If there is no written content below, it will also be written directly by closing writer.close(); // Close the write stream and write the contents of the buffer to the file at the same time, so the above comment is omitted fop.close(); // Close the output stream and release system resources FileInputStream fip = new FileInputStream(f); // Building a FileInputStream object InputStreamReader reader = new InputStreamReader(fip, "UTF-8"); // Build 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 read stream fip.close(); // Close the input stream and release system resources } }

Directories in Java

Create directory:

There are two methods in the File class that can be used to create folders:

  • The mkdir() method creates a folder, returns true if successful, and false if failed. Failure indicates that the path specified by the File object already exists, or the folder cannot be created because the entire path does not 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".

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

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, 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:

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("catalogue " + 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] + " It's a file"); } } } else { System.out.println(dirname + " Not a directory"); } } }

The compilation and operation results of the above examples are as follows:

catalogue /tmp bin Is a directory lib Is a directory demo Is a directory test.txt It's a file README It's a file index.html It's a file include Is a directory

Delete directory or file

Delete files can be used   java.io.File.delete()   method.

The following code will delete the directory  / tmp/java /, it should be noted that when deleting a directory, you must ensure that there are no other files in the directory to delete correctly, otherwise the deletion will fail.

Test directory structure:

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

DeleteFileDemo.java file code:

import java.io.File; public class DeleteFileDemo { public static void main(String[] args) { // Change here to your own test directory File folder = new File("/tmp/java/"); deleteFolder(folder); } // Delete files and directories 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(); } }

18 October 2021, 02:22 | Views: 6742

Add new comment

For adding a comment, please log in
or create account

0 comments