驚呆了,原來JavaIO如此簡單【奔跑吧!JAVA】
前言:
群里有大佬說想讓我寫一篇NIO,一直也沒寫,但是和同事聊天也說對Java的IO不是很清晰,因此今天就寫下Java的IO,先打個基礎,下次寫NIO,我們開始吧
一、IO底層是怎么回事?
二、梳理類的結構
三、IO類大點兵
四、來波實例展示
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 拷貝文件 * @author 香菜 */ public class CopyFileWithStream { public static void main(String[] args) { int b = 0; String inFilePath = "D:\\wechat\\A.txt"; String outFilePath = "D:\\wechat\\B.txt"; try (FileInputStream in = new FileInputStream(inFilePath); FileOutputStream out = new FileOutputStream(outFilePath)) { while ((b = in.read()) != -1) { out.write(b); } } catch (IOException e) { e.printStackTrace(); } System.out.println("文件復制完成"); } }
package org.pdool.iodoc; import java.io.*; /** * 拷貝文件 * * @author 香菜 */ public class CopyFileWithBuffer { public static void main(String[] args) throws Exception { String inFilePath = "D:\\wechat\\A.txt"; String outFilePath = "D:\\wechat\\B.txt"; try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFilePath)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFilePath))) { byte[] b = new byte[1024]; int off = 0; while ((off = bis.read(b)) > 0) { bos.write(b, 0, off); } } } }
import java.util.Scanner; public class TestScanner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()){ System.out.println(scanner.nextLine()); } } }
總結:
而Reader/Writer則是用于操作字符,增加了字符編解碼等功能,適用于類似從文件中讀取或者寫入文本信息。本質上計算機操作的都是字節,不管是網絡通信還是文件讀取,Reader/Writer相當于構建了應用邏輯和原始數據之間的橋梁。
Buffered等帶緩沖區的實現,可以避免頻繁的磁盤讀寫,進而提高IO處理效率。
記住IO流的設計模式是裝飾器模式,對流進行功能升級。
stream,reader ,buffered 三個關鍵詞記住
【奔跑吧!JAVA】有獎征文火熱進行中:https://bbs.huaweicloud.com/blogs/265241
Java 任務調度
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。