Input and output stream operation in Java core framework
Input and output stream operation in Java core framework
Java is a widely used programming language, which provides a wealth of core framework, including input and output flow operations.The input and output stream operation is a technology often used in programming, which is used to read and write data, so that the program can interact with the external environment.
Java's input and output stream is based on byte flow and character flow.Byte flow is used to process binary data, and character streams are used to process text data.By using the input stream, the program can obtain data from the outside and read it into the memory, and the output stream can write the data in the memory into the external device, such as disk files or network connection.
The example code of the input flow operation is as follows:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamExample {
public static void main(String[] args) {
try {
InputStream inputStream = new FileInputStream("input.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above sample code, we use an INPUTSTREAM object to read the file named "Input.txt".By calling the read () method, we can read the data in the file by byte and convert it into character output.The whole loop in the program will be executed until the end of the file is read.
The example code of the output stream operation is as follows:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamExample {
public static void main(String[] args) {
try {
OutputStream outputStream = new FileOutputStream("output.txt");
String data = "Hello, world!";
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above sample code, we used an OutputStream object to write data to the file named "Output.txt".By calling the WRITE () method, we can convert the string to byte array and write it into the file.The program will write "Hello, World!" Into the file and then turn off the output stream.
Java's input and output streaming operation enables the program to exchange data with the external environment.By using the input output streaming operation reasonably, we can implement various functions, such as file reading and writing, network communication, etc.In actual development, we need to choose the appropriate input and output stream according to specific needs to achieve the function of the program.