Java常用數(shù)據(jù)流全面大梳理
緩沖流
為了提高數(shù)據(jù)讀寫的速度,Java API提供了帶緩沖功能的流類,在使用這些流類時,會創(chuàng)建一個內(nèi)部緩沖區(qū)數(shù)組,缺省使用8192個字節(jié)(8Kb)的緩沖區(qū)。
緩沖流要“套接”在相應(yīng)的節(jié)點流之上,根據(jù)數(shù)據(jù)操作單位可以把緩沖流分為:
BufferedInputStream
和 BufferedOutputStream
BufferedReader
和 BufferedWriter
當(dāng)讀取數(shù)據(jù)時,數(shù)據(jù)按塊讀入緩沖區(qū),其后的讀操作則直接訪問緩沖區(qū)。當(dāng)使用BufferedInputStream讀取字節(jié)文件時,BufferedInputStream會一次性從文件中讀取8192個(8Kb),存在緩沖區(qū)中,直到緩沖區(qū)裝滿了,才重新從文件中讀取下一個8192個字節(jié)數(shù)組。
向流中寫入字節(jié)時,不會直接寫到文件,先寫到緩沖區(qū)中直到緩沖區(qū)寫滿,
BufferedOutputStream才會把緩沖區(qū)中的數(shù)據(jù)一次性寫到文件里。使用方法
flush()
可以強制將緩沖區(qū)的內(nèi)容全部寫入輸出流。
關(guān)閉流的順序和打開流的順序相反。只要關(guān)閉最外層流即可,關(guān)閉最外層流也
會相應(yīng)關(guān)閉內(nèi)層節(jié)點流。
flush()
方法的使用:手動將buffer中內(nèi)容寫入文件。使用帶緩沖區(qū)的流對象的close()
方法,不但會關(guān)閉流,還會在關(guān)閉流之前刷新緩沖區(qū),相當(dāng)于自動調(diào)用了flush()
方法,關(guān)閉后不能再寫出。
以字節(jié)流BufferedInputStream
和 BufferedOutputStream
示例具體操作:
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-25-22:36 * @Description: */ public class BufferedTest { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bfi = null; BufferedOutputStream bfo = null; try { //1、實例化File對象,指定文件 File inFile = new File("IO\\input.jpg"); File outFile = new File("IO\\output.jpg"); //2、創(chuàng)建節(jié)點流(文件流)對象 fis = new FileInputStream(inFile); fos = new FileOutputStream(outFile); //3、創(chuàng)建處理節(jié)點流的緩沖流對象 bfi = new BufferedInputStream(fis); bfo = new BufferedOutputStream(fos); //4、通過緩沖流進行讀寫操作 byte[] bytes = new byte[1024]; int length = bfi.read(bytes); while (length != -1){ bfo.write(bytes,0,length); length = bfi.read(bytes); } } catch (IOException e) { e.printStackTrace(); } finally { //5、關(guān)閉外層流,內(nèi)存流便自動關(guān)閉 try { if (bfi != null) bfi.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bfo != null) bfo.close(); } catch (IOException e) { e.printStackTrace(); } } } }
轉(zhuǎn)換流
轉(zhuǎn)換流提供了在字節(jié)流和字符流之間的轉(zhuǎn)換。
InputStreamReader
:將InputStream轉(zhuǎn)換為Reader(字節(jié)轉(zhuǎn)為字符輸入)
OutputStreamWriter
:將Writer轉(zhuǎn)換為OutputStream(字節(jié)轉(zhuǎn)為字符輸出)
字節(jié)流中的數(shù)據(jù)都是字符時,轉(zhuǎn)成字符流操作更高效。使用轉(zhuǎn)換流來處理文件亂碼問題,實現(xiàn)編碼和解碼的功能。
InputStreamReader:
實現(xiàn)將字節(jié)的輸入流按指定字符集轉(zhuǎn)換為字符的輸入流。需要和InputStream
“套接”。
構(gòu)造器:
public InputStreamReader(InputStream in)
public InputSreamReader(InputStream in,String charsetName)
OutputStreamWriter:
實現(xiàn)將字符的輸出流按指定字符集轉(zhuǎn)換為字節(jié)的輸出流。需要和OutputStream
“套接”。
構(gòu)造器:
public OutputStreamWriter(OutputStream out)
public OutputSreamWriter(OutputStream out,String charsetName)
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { InputStreamReader isr = null; OutputStreamWriter osw = null; try { //1、指明輸入輸出文件 File inFile = new File("IO\\hi.txt"); File outFile = new File("IO\\hello.txt"); //2、提供字節(jié)節(jié)點流 FileInputStream fis = new FileInputStream(inFile); FileOutputStream fos = new FileOutputStream(outFile); //3、提供轉(zhuǎn)換流 isr = new InputStreamReader(fis,"gbk"); osw = new OutputStreamWriter(fos,"utf-8"); //4、讀寫操作 char[] chars = new char[10]; int len = isr.read(chars); while (len != -1){ osw.write(chars,0,len); len = isr.read(chars); } } catch (IOException e) { e.printStackTrace(); } finally { //5、關(guān)閉外層流 try { if (osw != null) osw.close(); } catch (IOException e) { e.printStackTrace(); } try { if (isr != null) isr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
標準輸入輸出流
System.in
和System.out
分別代表了系統(tǒng)標準的輸入和輸出設(shè)備
默認輸入設(shè)備是:鍵盤,輸出設(shè)備是:顯示器(控制臺)
System.in
的類型是InputStream
System.out
的類型是PrintStream,其是OutputStream的子類
重定向:通過System類的setIn()
,setOut()
方法對默認設(shè)備進行改變:
public static void setIn(InputStream in)
public static void setOut(PrintStream out)
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { BufferedReader bis = null; try { //1、提供轉(zhuǎn)換流(System.in是字節(jié)流,將其轉(zhuǎn)換為字符流) System.out.println("請輸入信息(退出輸入e或exit):"); InputStreamReader isr = new InputStreamReader(System.in); //2、提供緩沖流將輸入的一行讀取 bis = new BufferedReader(isr); //3、讀操作 String s = null; while ((s = bis.readLine()) != null){ if ("e".equalsIgnoreCase(s) || "exit".equalsIgnoreCase(s)){ System.out.println("程序結(jié)束,退出程序!"); break; } System.out.println("==" + s.toUpperCase()); System.out.println("繼續(xù)輸入(退出輸入e或exit):"); } } catch (IOException e) { e.printStackTrace(); } finally { //4、關(guān)閉外層流 try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
打印流
實現(xiàn)將基本數(shù)據(jù)類型的數(shù)據(jù)格式轉(zhuǎn)化為字符串輸出。
打印流:PrintStream
和PrintWriter
提供了一系列重載的print()
和println()
方法,用于多種數(shù)據(jù)類型的輸出:
PrintStream和PrintWriter的輸出不會拋出IOException異常,
PrintStream和PrintWriter有自動flush功能,
PrintStream打印的所有字符都使用平臺的默認字符編碼轉(zhuǎn)換為字節(jié)
在需要寫入字符而不是寫入字節(jié)的情況下,應(yīng)該使用PrintWriter類。
System.out返回的是PrintStream的實例。
常與System.out搭配使用,可以不在控制臺輸出,而是輸出到指定位置:
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(new File("IO\\text.txt")); // 創(chuàng)建打印輸出流,設(shè)置為自動刷新模式(寫入換行符或字節(jié) '\n' 時都會刷新輸出緩沖區(qū)) ps = new PrintStream(fos, true); if (ps != null) {// 把標準輸出流(控制臺輸出)改成文件 System.setOut(ps); } for (int i = 0; i <= 255; i++) { // 輸出ASCII字符 System.out.print((char) i); if (i % 50 == 0) { // 每50個數(shù)據(jù)一行 System.out.println(); // 換行 } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } }
數(shù)據(jù)流
為了方便地操作Java語言的基本數(shù)據(jù)類型和String的數(shù)據(jù),可以使用數(shù)據(jù)流。
數(shù)據(jù)流有兩個類:(用于讀取和寫出基本數(shù)據(jù)類型、String類的數(shù)據(jù))
DataInputStream
和 DataOutputStream
分別“套接”在 InputStream 和 OutputStream 子類的流上。
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { //寫 DataOutputStream dos = null; try { dos = new DataOutputStream(new FileOutputStream("IO\\test.txt")); dos.writeUTF("葉綠體"); dos.writeInt(22); dos.writeBoolean(true); } catch (IOException e) { e.printStackTrace(); } finally { try { if (dos != null) dos.close(); } catch (IOException e) { e.printStackTrace(); } } //讀 DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream("IO\\test.txt")); //注意讀的順序要和寫的順序一樣 String name = dis.readUTF(); int age = dis.readInt(); boolean isMan = dis.readBoolean(); System.out.println(name + age + isMan); } catch (IOException e) { e.printStackTrace(); } finally { try { if (dis != null) dis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
對象流
ObjectInputStream
和OjbectOutputSteam
用于存儲和讀取基本數(shù)據(jù)類型數(shù)據(jù)或?qū)ο蟮奶幚砹?。它的強大之處就是可以把Java中的對象寫入到數(shù)據(jù)源中,也能把對象從數(shù)據(jù)源中還原回來。
序列化:用ObjectOutputStream
類保存基本類型數(shù)據(jù)或?qū)ο蟮臋C制
反序列化:用ObjectInputStream
類讀取基本類型數(shù)據(jù)或?qū)ο蟮臋C制
ObjectOutputStream
和ObjectInputStream
不能序列化static
和transient
修飾的成員變量。
實現(xiàn)Serializable
或者Externalizable
兩個接口之一的類的對象才可序列化,關(guān)于對象序列化詳見:
可序列化對象:
import java.io.Serializable; /** * @Author: Yeman * @Date: 2021-09-27-8:27 * @Description: */ class pet implements Serializable { public static final long serialVersionUID = 999794470754667999L; private String name; public pet(String name) { this.name = name; } @Override public String toString() { return "pet{" + "name='" + name + '\'' + '}'; } } public class Person implements Serializable { public static final long serialVersionUID = 6849794470754667999L; private String name; private int age; private pet pet; public Person(String name, int age, pet pet) { this.name = name; this.age = age; this.pet = pet; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", pet=" + pet + '}'; } }
序列化(ObjectOutputStream):
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("IO\\test.txt")); oos.writeUTF(new String("你好世界!")); oos.flush(); oos.writeObject(new Person("Lily",20,new pet("Xinxin"))); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (oos != null) oos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
反序列化(ObjectInputStream):
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("IO\\test.txt")); String s = ois.readUTF(); Person o = (Person) ois.readObject(); System.out.println(o.toString()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
隨機存取文件流
RandomAccessFile
聲明在java.io
包下,但直接繼承于java.lang.Object
類。并且它實現(xiàn)了DataInput
、DataOutput
這兩個接口,也就意味著這個類既可以讀也可以寫。
RandomAccessFile類支持 “隨機訪問” 的方式,程序可以直接跳到文件的任意地方來讀寫文件:①支持只訪問文件的部分內(nèi)容②可以向已存在的文件后追加內(nèi)容③若文件不存在,則創(chuàng)建④若文件存在,則從指針位置開始覆蓋內(nèi)容,而不是覆蓋文件。
RandomAccessFile對象包含一個記錄指針,用以標示當(dāng)前讀寫處的位置,RandomAccessFile類對象可以自由移動記錄指針:
long getFilePointer()
:獲取文件記錄指針的當(dāng)前位置
void seek(long pos)
:將文件記錄指針定位到 pos 位置
構(gòu)造器:
public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)
創(chuàng)建 RandomAccessFile 類實例需要指定一個 mode 參數(shù),該參數(shù)指定 RandomAccessFile 的訪問模式:
如果模式為只讀r。則不會創(chuàng)建文件,而是會去讀取一個已經(jīng)存在的文件,如果讀取的文件不存在則會出現(xiàn)異常。 如果模式為rw讀寫。如果文件不存在則會去創(chuàng)建文件,如果存在則不會創(chuàng)建。
import java.io.*; /** * @Author: Yeman * @Date: 2021-09-26-20:13 * @Description: */ public class Test { public static void main(String[] args) { RandomAccessFile r1 = null; RandomAccessFile rw = null; try { r1 = new RandomAccessFile("IO\\input.jpg", "r"); rw = new RandomAccessFile("IO\\output.jpg", "rw"); byte[] bytes = new byte[1024]; int len = r1.read(bytes); while (len != -1){ rw.write(bytes,0,len); len = r1.read(bytes); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (rw != null) rw.close(); } catch (IOException e) { e.printStackTrace(); } try { if (r1 != null) r1.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java NIO
Java NIO (New IO,Non-Blocking IO)是從Java 1.4版本開始引入的一套新的IO API,可以替代標準的Java IO API。NIO與原來的IO有同樣的作用和目的,但是使用的方式完全不同,NIO支持面向緩沖區(qū)的(IO是面向流的)、基于通道的IO操作,NIO將以更加高效的方式進行文件的讀寫操作。
Java API中提供了兩套NIO,一套是針對標準輸入輸出NIO,另一套就是網(wǎng)絡(luò)編程NIO。
隨著 JDK 7 的發(fā)布,Java對NIO進行了極大的擴展,增強了對文件處理和文件系統(tǒng)特性的支持,以至于我們稱他們?yōu)?NIO.2。因為 NIO 提供的一些功能,NIO已經(jīng)成為文件處理中越來越重要的部分。
早期的Java只提供了一個File類來訪問文件系統(tǒng),但File類的功能比較有限,所提供的方法性能也不高。而且,大多數(shù)方法在出錯時僅返回失敗,并不會提供異常信息。
NIO. 2為了彌補這種不足,引入了Path接口,代表一個平臺無關(guān)的平臺路徑,描述了目錄結(jié)構(gòu)中文件的位置。Path可以看成是File類的升級版本,實際引用的資源也可以不存在。
在以前IO操作都是這樣寫的:
import java.io.File; File file = new File("index.html");
但在Java7 中,可以這樣寫:
import java.nio.file.Path; import java.nio.file.Paths; Path path = Paths.get("index.html");
同時,NIO.2在java.nio.file包下還提供了Files、Paths工具類,F(xiàn)iles包含了大量靜態(tài)的工具方法來操作文件;Paths則包含了兩個返回Path的靜態(tài)工廠方法。
Paths 類提供的靜態(tài) get() 方法用來獲取 Path 對象:
static Path get(String first, String … more)
: 用于將多個字符串串連成路徑
static Path get(URI uri)
: 返回指定uri對應(yīng)的Path路徑
到此這篇關(guān)于Java常用數(shù)據(jù)流全面大梳理的文章就介紹到這了,更多相關(guān)Java 數(shù)據(jù)流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis-Plus找不到Mapper.xml文件的幾種解決方法
mybatis-plus今天遇到一個問題,就是mybatis 沒有讀取到mapper.xml 文件,所以下面這篇文章主要給大家介紹了關(guān)于MyBatis-Plus找不到Mapper.xml文件的幾種解決方法,需要的朋友可以參考下2022-06-06淺析JavaWeb項目架構(gòu)之Redis分布式日志隊列
架構(gòu)、分布式、日志隊列,標題自己都看著唬人,其實就是一個日志收集的功能,只不過中間加了一個Redis做消息隊列罷了。下面通過本文給大家分享JavaWeb項目架構(gòu)之Redis分布式日志隊列,感興趣的朋友一起看看吧2018-01-01Java 多態(tài)中繼承的轉(zhuǎn)型詳解與用法分析
繼承是java面向?qū)ο缶幊碳夹g(shù)的一塊基石,因為它允許創(chuàng)建分等級層次的類。繼承就是子類繼承父類的特征和行為,使得子類對象(實例)具有父類的實例域和方法,或子類從父類繼承方法,使得子類具有父類相同的行為2021-10-10