Byte Stream
InputStream
FileInputStream: Read raw bytes from file system
import ; import ; public class ReadFileBytes { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("")) { int content; while ((content = ()) != -1) { ((char) content); } } catch (IOException e) { (); } } }
ByteArrayInputStream: Allows programs to read data from a byte array
import ; public class ReadByteArray { public static void main(String[] args) { byte[] buffer = "Hello, World!".getBytes(); try (ByteArrayInputStream bis = new ByteArrayInputStream(buffer)) { int data; while ((data = ()) != -1) { ((char) data); } } } }
BufferedInputStream: Add buffering function to other input streams
import ; import ; import ; public class BufferedRead { public static void main(String[] args) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(""))) { int content; while ((content = ()) != -1) { ((char) content); } } catch (IOException e) { (); } } }
ObjectInputStream: Used to deserialize objects
import ; import ; import ; import ; class Person implements Serializable { private static final long serialVersionUID = 1L; String name; Person(String name) { = name; } } public class DeserializeObject { public static void main(String[] args) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(""))) { Person person = (Person) (); (); } catch (IOException | ClassNotFoundException e) { (); } } }
OutputStream
FileOutputStream: Write raw bytes to files in the file system
import ; import ; public class WriteFileBytes { public static void main(String[] args) { String data = "Hello, World!"; byte[] buffer = (); try (FileOutputStream fos = new FileOutputStream("")) { (buffer); } catch (IOException e) { (); } } }
ByteArrayOutputStream: Write output data to a byte array
import ; public class WriteByteArray { public static void main(String[] args) { String data = "Hello, World!"; byte[] buffer = (); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { (buffer); byte[] output = (); (new String(output)); } } }
BufferedOutputStream: Provides buffers for other output streams
import ; import ; import ; public class BufferedWrite { public static void main(String[] args) { String data = "Hello, World!\n"; byte[] buffer = (); try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(""))) { (buffer); } catch (IOException e) { (); } } }
ObjectOutputStream: Used to serialize objects
import ; import ; import ; import ; class Person implements Serializable { private static final long serialVersionUID = 1L; String name; Person(String name) { = name; } } public class SerializeObject { public static void main(String[] args) { Person person = new Person("Alice"); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(""))) { (person); } catch (IOException e) { (); } } }
Character stream
Input Stream (Reader)
FileReader: simplifies the process of reading characters from a file
import ; import ; import ; public class ReadFileChars { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader(""))) { String line; while ((line = ()) != null) { (line); } } catch (IOException e) { (); } } }
CharArrayReader: Read characters from character array
import ; public class ReadCharArray { public static void main(String[] args) { char[] chars = "Hello, World!".toCharArray(); try (CharArrayReader car = new CharArrayReader(chars)) { int c; while ((c = ()) != -1) { ((char) c); } } } }
BufferedReader: Add a buffer for other character input streams
import ; import ; import ; public class BufferedCharRead { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader(""))) { String line; while ((line = ()) != null) { (line); } } catch (IOException e) { (); } } }
InputStreamReader: Bridge, converting byte streams into character streams
import ; import ; import ; public class ByteToChar { public static void main(String[] args) { try (InputStreamReader isr = new InputStreamReader(new FileInputStream(""), "UTF-8")) { int c; while ((c = ()) != -1) { ((char) c); } } catch (IOException e) { (); } } }
Output Stream (Writer)
FileWriter: Simplifies the process of writing characters to files
import ; import ; public class WriteFileChars { public static void main(String[] args) { String data = "Hello, World!\n"; try (FileWriter writer = new FileWriter("", true)) { //Add mode (data); } catch (IOException e) { (); } } }
CharArrayWriter: Write characters to character array
import ; public class WriteCharArray { public static void main(String[] args) { String data = "Hello, World!"; try (CharArrayWriter caw = new CharArrayWriter()) { (data); char[] output = (); (new String(output)); } } }
BufferedWriter: Add a buffer for other character output streams
import ; import ; import ; public class BufferedCharWrite { public static void main(String[] args) { String data = "Hello, World!\n"; try (BufferedWriter bw = new BufferedWriter(new FileWriter("", true))) { (data); (); // Write newline characters } catch (IOException e) { (); } } }
OutputStreamWriter: Bridge, converting character streams into byte streams
import ; import ; import ; public class CharToByte { public static void main(String[] args) { String data = "Hello, World!"; try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(""), "UTF-8")) { (data); } catch (IOException e) { (); } } }
Advanced Features
Piped Streams: Pipeline flow allows one thread to send data to another thread through a pipeline
import ; import ; import ; class Producer implements Runnable { private PipedOutputStream pos; Producer(PipedInputStream pis) throws IOException { pos = new PipedOutputStream(pis); } @Override public void run() { try { String data = "Hello, Pipe!"; (()); (); } catch (IOException e) { (); } } } class Consumer implements Runnable { private PipedInputStream pis; Consumer(PipedOutputStream pos) throws IOException { pis = new PipedInputStream(pos); } @Override public void run() { try { int data; while ((data = ()) != -1) { ((char) data); } (); } catch (IOException e) { (); } } } public class PipeStreams { public static void main(String[] args) throws IOException { PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(pis); Thread producerThread = new Thread(new Producer(pos)); Thread consumerThread = new Thread(new Consumer(pis)); (); (); } }
PrintStream: Format output stream, usually used for standard output (console)
import ; import ; import ; public class UsePrintStream { public static void main(String[] args) { try (PrintStream ps = new PrintStream(new FileOutputStream(""))) { ("Hello, PrintStream!"); ("This is a formatted string: %d%%\n", 100); } catch (IOException e) { (); } } }
Scanner: used to parse basic data types and strings
import ; import ; import ; public class UseScanner { public static void main(String[] args) { try (Scanner scanner = new Scanner(new File(""))) { while (()) { String line = (); (line); } } catch (IOException e) { (); } } }
Formatter: Format the output
import ; import ; public class UseFormatter { public static void main(String[] args) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ("Hello, %s!\n", "Formatter"); ("Formatted integer: %d\n", 42); (()); } }
NIO (New IO)
Channels and Buffers
Read and write files using FileChannel and ByteBuffer
import ; import ; import ; import ; import ; import ; import ; public class NIOExample { public static void main(String[] args) { Path path = (""); String data = "Hello NIO!"; // Writing to file using FileChannel and ByteBuffer try (FileChannel channel = (path, , )) { ByteBuffer buffer = (1024); ((StandardCharsets.UTF_8)); (); // Switch to read mode (buffer); } catch (IOException e) { (); } // Reading from file using FileChannel and ByteBuffer try (FileChannel channel = (path)) { ByteBuffer buffer = (1024); int bytesRead = (buffer); (); // Switch to read mode byte[] bytes = new byte[bytesRead]; (bytes); (new String(bytes, StandardCharsets.UTF_8)); } catch (IOException e) { (); } } }
Selectors
The use of selectors is slightly more complicated, and it is mainly used in network programming to implement non-blocking I/O. Here is a simple example to show how to create and use selectors to monitor multipleSocketChannel
。
import ; import ; import ; import ; import ; import ; import ; public class SelectorExample { public static void main(String[] args) throws IOException { // Open a selector Selector selector = ().openSelector(); // Open a server socket channel and bind it to port 8080 ServerSocketChannel serverChannel = (); ().bind(new InetSocketAddress(8080)); (false); // Register the server channel with the selector for accepting connections (selector, SelectionKey.OP_ACCEPT); // Loop indefinitely, waiting for events on the channels registered with the selector while (true) { // Wait for at least one event (); // Get the set of keys with pending events for (SelectionKey key : ()) { // Remove the current key from the set so it won't be processed again ().remove(key); if (!()) { continue; } // Check what event is ready and handle it if (()) { // Accept the new connection ServerSocketChannel ssc = (ServerSocketChannel) (); SocketChannel sc = (); (false); // Register the new SocketChannel with the selector for reading (selector, SelectionKey.OP_READ); } else if (()) { // Read the data from the client SocketChannel sc = (SocketChannel) (); // ... handle reading ... } } } } }
Summarize
This is the end of this article about the comprehensive application of Java IO streaming and NIO technology. For more related Java IO streaming and NIO technology application content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!