Java?IO流與NIO技術(shù)綜合應(yīng)用詳細(xì)實(shí)例代碼
字節(jié)流
輸入流(InputStream)
FileInputStream:從文件系統(tǒng)中讀取原始字節(jié)
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileBytes {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt")) {
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ByteArrayInputStream:允許程序從一個(gè)字節(jié)數(shù)組中讀取數(shù)據(jù)
import java.io.ByteArrayInputStream;
public class ReadByteArray {
public static void main(String[] args) {
byte[] buffer = "Hello, World!".getBytes();
try (ByteArrayInputStream bis = new ByteArrayInputStream(buffer)) {
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
}
}
}
BufferedInputStream:為其他輸入流添加緩沖功能
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class BufferedRead {
public static void main(String[] args) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"))) {
int content;
while ((content = bis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectInputStream:用于反序列化對(duì)象
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
Person(String name) {
this.name = name;
}
}
public class DeserializeObject {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person person = (Person) ois.readObject();
System.out.println(person.name);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
輸出流(OutputStream)
FileOutputStream:向文件系統(tǒng)中的文件寫(xiě)入原始字節(jié)
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileBytes {
public static void main(String[] args) {
String data = "Hello, World!";
byte[] buffer = data.getBytes();
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
fos.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ByteArrayOutputStream:將輸出的數(shù)據(jù)寫(xiě)入到字節(jié)數(shù)組中
import java.io.ByteArrayOutputStream;
public class WriteByteArray {
public static void main(String[] args) {
String data = "Hello, World!";
byte[] buffer = data.getBytes();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
baos.write(buffer);
byte[] output = baos.toByteArray();
System.out.println(new String(output));
}
}
}
BufferedOutputStream:為其他輸出流提供緩沖區(qū)
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedWrite {
public static void main(String[] args) {
String data = "Hello, World!\n";
byte[] buffer = data.getBytes();
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
bos.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectOutputStream:用于序列化對(duì)象
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
Person(String name) {
this.name = name;
}
}
public class SerializeObject {
public static void main(String[] args) {
Person person = new Person("Alice");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流
輸入流(Reader)
FileReader:簡(jiǎn)化了從文件讀取字符的過(guò)程
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadFileChars {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
CharArrayReader:從字符數(shù)組中讀取字符
import java.io.CharArrayReader;
public class ReadCharArray {
public static void main(String[] args) {
char[] chars = "Hello, World!".toCharArray();
try (CharArrayReader car = new CharArrayReader(chars)) {
int c;
while ((c = car.read()) != -1) {
System.out.print((char) c);
}
}
}
}
BufferedReader:為其他字符輸入流添加緩沖區(qū)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedCharRead {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStreamReader:橋接器,將字節(jié)流轉(zhuǎn)換為字符流
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
public class ByteToChar {
public static void main(String[] args) {
try (InputStreamReader isr = new InputStreamReader(new FileInputStream("input.txt"), "UTF-8")) {
int c;
while ((c = isr.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
輸出流(Writer)
FileWriter:簡(jiǎn)化了將字符寫(xiě)入文件的過(guò)程
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileChars {
public static void main(String[] args) {
String data = "Hello, World!\n";
try (FileWriter writer = new FileWriter("output.txt", true)) { // 追加模式
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
CharArrayWriter:將字符寫(xiě)入字符數(shù)組
import java.io.CharArrayWriter;
public class WriteCharArray {
public static void main(String[] args) {
String data = "Hello, World!";
try (CharArrayWriter caw = new CharArrayWriter()) {
caw.write(data);
char[] output = caw.toCharArray();
System.out.println(new String(output));
}
}
}
BufferedWriter:為其他字符輸出流添加緩沖區(qū)
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedCharWrite {
public static void main(String[] args) {
String data = "Hello, World!\n";
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true))) {
bw.write(data);
bw.newLine(); // 寫(xiě)入換行符
} catch (IOException e) {
e.printStackTrace();
}
}
}
OutputStreamWriter:橋接器,將字符流轉(zhuǎn)換為字節(jié)流
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class CharToByte {
public static void main(String[] args) {
String data = "Hello, World!";
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8")) {
osw.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
高級(jí)特性
Piped Streams:管道流使得一個(gè)線程可以通過(guò)管道將數(shù)據(jù)發(fā)送給另一個(gè)線程
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.IOException;
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!";
pos.write(data.getBytes());
pos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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 = pis.read()) != -1) {
System.out.print((char) data);
}
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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));
producerThread.start();
consumerThread.start();
}
}
PrintStream:格式化輸出流,通常用于標(biāo)準(zhǔn)輸出(控制臺(tái))
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class UsePrintStream {
public static void main(String[] args) {
try (PrintStream ps = new PrintStream(new FileOutputStream("output.txt"))) {
ps.println("Hello, PrintStream!");
ps.printf("This is a formatted string: %d%%\n", 100);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Scanner:用于解析基礎(chǔ)數(shù)據(jù)類(lèi)型和字符串
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class UseScanner {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("input.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Formatter:用于格式化輸出
import java.io.PrintWriter;
import java.io.StringWriter;
public class UseFormatter {
public static void main(String[] args) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.format("Hello, %s!\n", "Formatter");
pw.format("Formatted integer: %d\n", 42);
System.out.println(sw.toString());
}
}
NIO (New IO)
Channels 和 Buffers
使用FileChannel和ByteBuffer讀寫(xiě)文件
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
public class NIOExample {
public static void main(String[] args) {
Path path = Paths.get("output.txt");
String data = "Hello NIO!";
// Writing to file using FileChannel and ByteBuffer
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(data.getBytes(StandardCharsets.UTF_8));
buffer.flip(); // Switch to read mode
channel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
// Reading from file using FileChannel and ByteBuffer
try (FileChannel channel = FileChannel.open(path)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
buffer.flip(); // Switch to read mode
byte[] bytes = new byte[bytesRead];
buffer.get(bytes);
System.out.println(new String(bytes, StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Selectors
選擇器的使用稍微復(fù)雜一些,它主要用于網(wǎng)絡(luò)編程中,以實(shí)現(xiàn)非阻塞I/O。這里提供一個(gè)簡(jiǎn)單的例子來(lái)展示如何創(chuàng)建和使用選擇器監(jiān)控多個(gè)SocketChannel。
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.spi.SelectorProvider;
public class SelectorExample {
public static void main(String[] args) throws IOException {
// Open a selector
Selector selector = SelectorProvider.provider().openSelector();
// Open a server socket channel and bind it to port 8080
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.socket().bind(new InetSocketAddress(8080));
serverChannel.configureBlocking(false);
// Register the server channel with the selector for accepting connections
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
// Loop indefinitely, waiting for events on the channels registered with the selector
while (true) {
// Wait for at least one event
selector.select();
// Get the set of keys with pending events
for (SelectionKey key : selector.selectedKeys()) {
// Remove the current key from the set so it won't be processed again
selector.selectedKeys().remove(key);
if (!key.isValid()) {
continue;
}
// Check what event is ready and handle it
if (key.isAcceptable()) {
// Accept the new connection
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
// Register the new SocketChannel with the selector for reading
sc.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
// Read the data from the client
SocketChannel sc = (SocketChannel) key.channel();
// ... handle reading ...
}
}
}
}
}總結(jié)
到此這篇關(guān)于Java IO流與NIO技術(shù)綜合應(yīng)用的文章就介紹到這了,更多相關(guān)Java IO流與NIO技術(shù)應(yīng)用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot整合MybatisPlus的實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Springboot整合MybatisPlus的實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Java基礎(chǔ)教程之?dāng)?shù)組的定義與使用
Java語(yǔ)言的數(shù)組是一個(gè)由固定長(zhǎng)度的特定類(lèi)型元素組成的集合,它們的數(shù)據(jù)類(lèi)型必須相同,聲明變量的時(shí)候,必須要指定參數(shù)類(lèi)型,這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)教程之?dāng)?shù)組的定義與使用的相關(guān)資料,需要的朋友可以參考下2021-09-09
基于Spring框架由ConditionalOnMissingBean注解引發(fā)的問(wèn)題
這篇文章主要介紹了基于Spring框架由ConditionalOnMissingBean注解引發(fā)的問(wèn)題,具有很好2023-11-11
Mybatis中isNotNull與isNotEmpty的使用心得
這篇文章主要介紹了Mybatis中isNotNull與isNotEmpty的使用心得,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
淺談controller中調(diào)用多個(gè)service方法的問(wèn)題
這篇文章主要介紹了淺談controller中調(diào)用多個(gè)service方法的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
JVM(Java虛擬機(jī))簡(jiǎn)介(動(dòng)力節(jié)點(diǎn)Java學(xué)院整理)
Java虛擬機(jī)(Jvm)是可運(yùn)行Java代碼的假想計(jì)算機(jī)。Java虛擬機(jī)包括一套字節(jié)碼指令集、一組寄存器、一個(gè)棧、一個(gè)垃圾回收堆和一個(gè)存儲(chǔ)方法域。對(duì)java jvm 虛擬機(jī)感興趣的朋友通過(guò)本文一起學(xué)習(xí)吧2017-04-04
SpringBoot2.x 整合 thumbnailator 圖片處理的示例代碼
這篇文章主要介紹了SpringBoot2.x 之整合 thumbnailator 圖片處理,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
Java通過(guò)字節(jié)碼工具ASM實(shí)現(xiàn)類(lèi)的動(dòng)態(tài)增強(qiáng)
ASM 是一個(gè)輕量級(jí)、高性能的 Java 字節(jié)碼操控框架,它基于字節(jié)碼指令集操作,能夠直接讀取、修改和生成 Java 字節(jié)碼文件,下面我們來(lái)看看如何通過(guò)ASM實(shí)現(xiàn)類(lèi)的動(dòng)態(tài)增強(qiáng)吧2025-12-12
java創(chuàng)建子類(lèi)對(duì)象設(shè)置并調(diào)用父類(lèi)的變量操作
這篇文章主要介紹了java創(chuàng)建子類(lèi)對(duì)象設(shè)置并調(diào)用父類(lèi)的變量操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01

