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ù)類型和字符串
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接口如何對(duì)參數(shù)進(jìn)行校驗(yàn)
這篇文章主要介紹了SpringBoot接口如何對(duì)參數(shù)進(jìn)行校驗(yàn),在以SpringBoot開(kāi)發(fā)Restful接口時(shí),?對(duì)于接口的查詢參數(shù)后臺(tái)也是要進(jìn)行校驗(yàn)的,同時(shí)還需要給出校驗(yàn)的返回信息放到上文我們統(tǒng)一封裝的結(jié)構(gòu)中2022-07-07SpringBoot手動(dòng)開(kāi)啟事務(wù):DataSourceTransactionManager問(wèn)題
這篇文章主要介紹了SpringBoot手動(dòng)開(kāi)啟事務(wù):DataSourceTransactionManager問(wèn)題,具有很好的價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07Java編程中應(yīng)用的GUI設(shè)計(jì)基礎(chǔ)
這篇文章主要介紹了Java編程中應(yīng)用的GUI設(shè)計(jì)基礎(chǔ),為一些Java開(kāi)發(fā)CS類型應(yīng)用的基礎(chǔ)概念知識(shí),需要的朋友可以參考下2015-10-10idea每次新打開(kāi)的項(xiàng)目窗口maven都要重新設(shè)置問(wèn)題
這篇文章主要介紹了idea每次新打開(kāi)的項(xiàng)目窗口maven都要重新設(shè)置問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11maven一鍵刪除倉(cāng)庫(kù)無(wú)用文件的實(shí)現(xiàn)
大家都知道我們?cè)谑褂肕aven的時(shí)候,會(huì)下載一堆無(wú)用非jar文件,本文主要介紹了maven一鍵刪除倉(cāng)庫(kù)無(wú)用文件的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11MyEclipse整合ssh三大框架環(huán)境搭載用戶注冊(cè)源碼下載
這篇文章主要為大家詳細(xì)介紹了如何使用MyEclipse整合ssh三大框架進(jìn)行環(huán)境搭載,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10cmd中javac命令無(wú)法運(yùn)行(java指令能運(yùn)行)解決步驟
這篇文章主要介紹了在安裝JDK后,執(zhí)行javac命令沒(méi)有返回值的問(wèn)題,可能是由于命令提示符窗口緩存問(wèn)題、系統(tǒng)路徑優(yōu)先級(jí)問(wèn)題、文件權(quán)限問(wèn)題或命令行輸入問(wèn)題,文中通過(guò)代碼將解決的步驟介紹的非常詳細(xì),需要的朋友可以參考下2025-02-02JAVA設(shè)計(jì)模式之調(diào)停者模式詳解
這篇文章主要介紹了JAVA設(shè)計(jì)模式之調(diào)停者模式詳解,調(diào)停者模式是對(duì)象的行為模式,調(diào)停者模式包裝了一系列對(duì)象相互作用的方式,使得這些對(duì)象不必相互明顯引用,從而使它們可以較松散地耦合,需要的朋友可以參考下2015-04-04Java多線程連續(xù)打印abc實(shí)現(xiàn)方法詳解
這篇文章主要介紹了Java多線程連續(xù)打印abc實(shí)現(xiàn)方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03SpringCloud微服務(wù)基礎(chǔ)簡(jiǎn)介
今天帶大家學(xué)習(xí)一下SpringCloud微服務(wù)的相關(guān)知識(shí),文中有非常詳細(xì)的圖文示例及介紹,對(duì)正在學(xué)習(xí)SpringCloud微服務(wù)的小伙伴們很有幫助哦,需要的朋友可以參考下2021-05-05