Java?IO流與NIO技術(shù)綜合應(yīng)用詳細(xì)實例代碼
字節(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:允許程序從一個字節(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:用于反序列化對象
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)中的文件寫入原始字節(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ù)寫入到字節(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:用于序列化對象
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:簡化了從文件讀取字符的過程
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:簡化了將字符寫入文件的過程
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:將字符寫入字符數(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(); // 寫入換行符 } 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(); } } }
高級特性
Piped Streams:管道流使得一個線程可以通過管道將數(shù)據(jù)發(fā)送給另一個線程
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)輸出(控制臺)
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ù)類型和字符串
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讀寫文件
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ò)編程中,以實現(xiàn)非阻塞I/O。這里提供一個簡單的例子來展示如何創(chuàng)建和使用選擇器監(jiān)控多個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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot手動開啟事務(wù):DataSourceTransactionManager問題
這篇文章主要介紹了SpringBoot手動開啟事務(wù):DataSourceTransactionManager問題,具有很好的價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Java編程中應(yīng)用的GUI設(shè)計基礎(chǔ)
這篇文章主要介紹了Java編程中應(yīng)用的GUI設(shè)計基礎(chǔ),為一些Java開發(fā)CS類型應(yīng)用的基礎(chǔ)概念知識,需要的朋友可以參考下2015-10-10idea每次新打開的項目窗口maven都要重新設(shè)置問題
這篇文章主要介紹了idea每次新打開的項目窗口maven都要重新設(shè)置問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11MyEclipse整合ssh三大框架環(huán)境搭載用戶注冊源碼下載
這篇文章主要為大家詳細(xì)介紹了如何使用MyEclipse整合ssh三大框架進行環(huán)境搭載,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10cmd中javac命令無法運行(java指令能運行)解決步驟
這篇文章主要介紹了在安裝JDK后,執(zhí)行javac命令沒有返回值的問題,可能是由于命令提示符窗口緩存問題、系統(tǒng)路徑優(yōu)先級問題、文件權(quán)限問題或命令行輸入問題,文中通過代碼將解決的步驟介紹的非常詳細(xì),需要的朋友可以參考下2025-02-02Java多線程連續(xù)打印abc實現(xiàn)方法詳解
這篇文章主要介紹了Java多線程連續(xù)打印abc實現(xiàn)方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03