java常用數(shù)據(jù)流應(yīng)用實(shí)例解析
這篇文章主要介紹了java常用數(shù)據(jù)流應(yīng)用實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
按操作單位的不同分為:字節(jié)流(8bit)(InputStream、OuputStream)、字符流(16bit)(Reader、Writer)
按數(shù)據(jù)流的流向不同分為:輸入流、輸出流
按角色的不同分為:節(jié)點(diǎn)流、處理流
一、不帶緩沖的流
1.文件字節(jié)輸入流、文件字節(jié)輸出流
package anno; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Test2 { public static void main(String[] args) { test1FileInputStream(); test2FileInputStream(); testFileOutputStream(); } public static void test1FileInputStream() { String path = "F:\\test.txt"; try { FileInputStream fs = new FileInputStream(path); //設(shè)置一個(gè)數(shù)組接收文件的內(nèi)容 //需要注意的是,如果數(shù)組設(shè)置的太小,那么可能出現(xiàn)讀取的數(shù)據(jù)不完整或者亂碼等情況 byte[] b = new byte[30]; //文件輸入流對(duì)象有一個(gè)返回值,返回的是讀取數(shù)據(jù)的長(zhǎng)度,如果讀取到一個(gè)數(shù)據(jù)了,還會(huì)向后讀一個(gè), //當(dāng)讀取完畢時(shí)會(huì)返回-1 int len = 0; while((len=fs.read(b))!=-1) { //參數(shù)1是緩沖數(shù)據(jù)數(shù)組,參數(shù)2是從哪個(gè)位置開(kāi)始轉(zhuǎn)換成字符串,參數(shù)3是總共轉(zhuǎn)換的長(zhǎng)度 System.out.println(new String(b, 0, len)); } fs.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void test2FileInputStream() { String path = "F:\\test.txt"; File f = new File(path); int l = (int) f.length(); try { FileInputStream fs = new FileInputStream(path); byte[] b = new byte[l]; //將讀取的數(shù)據(jù)存入到b中 fs.read(b); //將b轉(zhuǎn)換成字符串并輸出 System.out.println(new String(b)); fs.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void testFileOutputStream() { //如果不存在該文件,則系統(tǒng)會(huì)新建一個(gè) String path1 = "F:\\test2.txt"; try { FileOutputStream fo = new FileOutputStream(path1); String str = "這是我測(cè)試的輸入"; fo.write(str.getBytes());//將數(shù)據(jù)寫(xiě)到byte中 fo.flush();//將內(nèi)存中的數(shù)據(jù)寫(xiě)到文件中 fo.close();//關(guān)閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
在運(yùn)行的過(guò)程中會(huì)遇到一些問(wèn)題,比如說(shuō)設(shè)置的byte數(shù)組來(lái)接收讀取的數(shù)據(jù),如果初始化長(zhǎng)度給的比較小,那么讀取的數(shù)據(jù)就不全,在進(jìn)行test1FileInputStream()的實(shí)驗(yàn)中,即使按照:
int len = 0; while((len=fs.read(b))!=-1) { //參數(shù)1是緩沖數(shù)據(jù)數(shù)組,參數(shù)2是從哪個(gè)位置開(kāi)始轉(zhuǎn)換成字符串,參數(shù)3是總共轉(zhuǎn)換的長(zhǎng)度 System.out.println(new String(b, 0, len)); }
進(jìn)行輸出,如果byte設(shè)置的還是太小,就會(huì)出現(xiàn):
這是我新建的test.txt�
��件
這種亂碼問(wèn)題,于是進(jìn)行了第二種方法的嘗試,即在傳入數(shù)據(jù)之前首先獲得要接收多少字節(jié)的數(shù)據(jù),然后在進(jìn)行接收(借鑒之前在golang中文件讀取并顯示的思想),然后就沒(méi)有問(wèn)題了,即test2FileInputStream()。
輸出結(jié)果:
這是我新建的test.txt文件
2.使用字節(jié)流將一個(gè)文件復(fù)制到指定的文件夾下
public static void copyFile() { String path = "F:\\test.txt"; String path2 = "F:\\test2.txt"; try { FileInputStream fi = new FileInputStream(path); FileOutputStream fo = new FileOutputStream(path2); File f = new File(path); int l = (int) f.length(); byte[] b = new byte[l]; int len = 0; while((len=fi.read(b))!=-1) { fo.write(b,0,len); } fo.flush(); fo.close(); fi.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
綜合使用之前讀取的方式。
3.文件字符輸入流、文件字符輸出流
public static void testFileReader() { String path = "F:\\test.txt"; try { FileReader fr = new FileReader(path); //注意這里是char類(lèi)型的數(shù)組了 char[] c = new char[20]; int len = 0; while((len=fr.read(c))!=-1) { System.out.println(new String(c, 0, len)); } fr.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void testFileWriter() { String path1 = "F:\\test2.txt"; try { FileWriter fw = new FileWriter(path1); String str = "這是我測(cè)試的輸入"; //注意這里可以直接寫(xiě)入字符串 fw.write(str); fw.flush();//將內(nèi)存中的數(shù)據(jù)寫(xiě)到文件中 fw.close();//關(guān)閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
需要注意的是定義char數(shù)組時(shí)仍然是需要知道數(shù)據(jù)是有多少字符的,不然長(zhǎng)度不夠,顯示不全或者寫(xiě)入不全。(這里暫時(shí)還未了解怎么處理)
4.使用字符流將一個(gè)文件復(fù)制到指定的文件夾下
public static void copyFile2() { String path = "F:\\test.txt"; String path2 = "F:\\test2.txt"; try { FileReader fr = new FileReader(path); FileWriter fw = new FileWriter(path2); char[] c = new char[30]; int len = 0; while((len=fr.read(c))!=-1) { fw.write(c,0,len); } fw.flush(); fw.close(); fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
二、帶緩沖的流
為了提高數(shù)據(jù)的讀寫(xiě)速度,java API提供了帶緩沖功能的流類(lèi),在使用這些流類(lèi)時(shí),會(huì)創(chuàng)建一個(gè)內(nèi)部緩沖區(qū)數(shù)組。
根據(jù)數(shù)據(jù)操作單位可以把緩沖流分為:BufferedInputStream/BufferedOutputStream和BufferedReader/BufferedWriter。
緩沖流要“套接”在相應(yīng)的節(jié)點(diǎn)流之上,對(duì)讀寫(xiě)的數(shù)據(jù)提供了緩沖的功能,提高了讀寫(xiě)的效率,同時(shí)增加了些新方法。對(duì)于輸出的緩沖流,寫(xiě)出的數(shù)據(jù)都會(huì)先在內(nèi)存中緩存,使用flush()會(huì)將在內(nèi)存中的數(shù)據(jù)立即寫(xiě)出。
1.緩沖字節(jié)輸入流、緩沖字節(jié)輸出流
package anno; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Test4 { public static void main(String[] args) throws IOException { testBufferedInputStream(); testBufferedOutputStream(); copyFile(); } public static void testBufferedInputStream() throws IOException { FileInputStream fi = new FileInputStream("F:\\test.txt"); //把文件字節(jié)輸入流放入到緩沖輸入流中 BufferedInputStream bi = new BufferedInputStream(fi); byte[] b = new byte[35]; int len = 0; while((len=bi.read(b))!=-1) { System.out.println(new String(b, 0, len)); } bi.close(); fi.close(); } public static void testBufferedOutputStream() throws IOException { FileOutputStream fo = new FileOutputStream("F:\\test3.txt"); //把文件字節(jié)輸入流放入到緩沖輸入流中 BufferedOutputStream bo = new BufferedOutputStream(fo); String str = "這是我測(cè)試的內(nèi)容"; bo.write(str.getBytes()); bo.flush(); bo.close(); fo.close(); } public static void copyFile() { String path = "F:\\test.txt"; String path2 = "F:\\test2.txt"; try { FileInputStream fi = new FileInputStream(path); BufferedInputStream bi = new BufferedInputStream(fi); FileOutputStream fo = new FileOutputStream(path2); BufferedOutputStream bo = new BufferedOutputStream(fo); File f = new File(path); int l = (int) f.length(); byte[] b = new byte[l]; int len = 0; while((len=bi.read(b))!=-1) { bo.write(b,0,len); } bo.flush(); bo.close(); fo.close(); bi.close(); fi.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2.緩沖字符輸入流、緩沖字符輸出流
package anno; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Test3 { public static void main(String[] args) { testBufferedReader(); testBufferedWriter(); copyFile(); } public static void testBufferedReader() { String path = "F:\\test.txt"; try { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); char[] c = new char[17]; int len = 0; while((len=br.read(c))!=-1) { System.out.println(new String(c, 0, len)); } br.close(); fr.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void testBufferedWriter() { String path1 = "F:\\test2.txt"; try { FileWriter fw = new FileWriter(path1); BufferedWriter bw = new BufferedWriter(fw); String str = "這是我測(cè)試的輸入"; bw.write(str);//將數(shù)據(jù)寫(xiě)到chars中 bw.flush();//將內(nèi)存中的數(shù)據(jù)寫(xiě)到文件中 bw.close(); fw.close();//關(guān)閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copyFile() { String path = "F:\\test.txt"; String path2 = "F:\\test2.txt"; try { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(path2); BufferedWriter bw = new BufferedWriter(fw); char[] c = new char[30]; int len = 0; while((len=br.read(c))!=-1) { bw.write(c,0,len); } bw.flush(); bw.close(); fw.close(); br.close(); fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
三、轉(zhuǎn)換流:用于字節(jié)流和字符流之間的轉(zhuǎn)換
java Api提供了兩個(gè)轉(zhuǎn)換流:InputStreamReader和OutputSreamWriter。
當(dāng)字節(jié)流中的數(shù)據(jù)都是字符時(shí),轉(zhuǎn)換成字符流操作更高效
package anno; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Test5 { public static void main(String[] args) throws IOException { testInputStreamReader(); testOutputStreamWriter(); } public static void testInputStreamReader() throws IOException { FileInputStream fi = new FileInputStream("F:\\test.txt"); //字節(jié)流轉(zhuǎn)換成字符流 //注意轉(zhuǎn)換成的編碼要和讀取的文件一致 InputStreamReader ir = new InputStreamReader(fi,"utf-8"); char[] c = new char[17]; int len = 0; while((len=ir.read(c))!=-1) { System.out.println(new String(c, 0, len)); } ir.close(); fi.close(); } public static void testOutputStreamWriter() throws IOException { FileOutputStream fo = new FileOutputStream("F:\\test3.txt"); //轉(zhuǎn)換字節(jié)輸出流為字符輸出流 OutputStreamWriter ow = new OutputStreamWriter(fo,"utf-8"); String str = "這是我測(cè)試的內(nèi)容"; ow.write(str); ow.flush(); ow.close(); fo.close(); } public static void copyFile() { String path = "F:\\test.txt"; String path2 = "F:\\test2.txt"; try { FileInputStream fi = new FileInputStream(path); BufferedInputStream bi = new BufferedInputStream(fi); FileOutputStream fo = new FileOutputStream(path2); BufferedOutputStream bo = new BufferedOutputStream(fo); File f = new File(path); int l = (int) f.length(); byte[] b = new byte[l]; int len = 0; while((len=bi.read(b))!=-1) { bo.write(b,0,len); } bo.flush(); bo.close(); fo.close(); bi.close(); fi.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
四、標(biāo)準(zhǔn)輸入輸出流
package anno; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Test6 { public static void main(String[] args) throws IOException { // testSystemIn(); testWriterToTxt(); } public static void testSystemIn() throws IOException { //創(chuàng)建一個(gè)獲取鍵盤(pán)輸入的輸入流 InputStreamReader ir = new InputStreamReader(System.in); //將輸入流放在緩沖中 BufferedReader br = new BufferedReader(ir); String str = ""; while((str = br.readLine())!=null) { System.out.println(str); } } //將控制臺(tái)的輸入寫(xiě)入到txt文件中 public static void testWriterToTxt() throws IOException { //創(chuàng)建一個(gè)獲取鍵盤(pán)輸入的輸入流 InputStreamReader ir = new InputStreamReader(System.in); //將輸入流放在緩沖中 BufferedReader br = new BufferedReader(ir); BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\test5.txt")); String line = ""; while((line = br.readLine())!=null) { if (line.equals("over")) { break; } bw.write(line); } bw.flush(); bw.close(); br.close(); ir.close(); } }
五、數(shù)據(jù)流
package anno; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Test7 { public static void main(String[] args) throws IOException { testDataOutputStream(); testDataInputStream(); } //用數(shù)據(jù)輸出流寫(xiě)到文件中的基本類(lèi)型數(shù)據(jù)是亂碼,不能辨認(rèn)出來(lái),需要數(shù)據(jù)輸入流讀取 public static void testDataOutputStream() throws IOException { DataOutputStream ds = new DataOutputStream(new FileOutputStream("F:\\test6.txt")); ds.writeDouble(1.35d); ds.flush(); ds.close(); } public static void testDataInputStream() throws IOException { DataInputStream ds = new DataInputStream(new FileInputStream("F:\\test6.txt")); System.out.println(ds.readDouble()); ds.close(); } }
六、對(duì)象流
用于存儲(chǔ)和讀取對(duì)象的處理流,它的強(qiáng)大之處就是可以把java中對(duì)象寫(xiě)入到數(shù)據(jù)源中,也能把對(duì)象從數(shù)據(jù)源中還原出來(lái)。
序列化:用ObjectOutputStream類(lèi)將一個(gè)對(duì)象下入io流中;
反序列化:用ObjectInputStream類(lèi)從io流中恢復(fù)對(duì)Java對(duì)象;
package anno; import java.io.Serializable; public class Person implements Serializable{ //用來(lái)標(biāo)識(shí)的UID private static final long serialVersionUID = 1L; String name; int age; }
package anno; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Test8 { public static void main(String[] args) throws IOException, ClassNotFoundException { // testSerializable(); testDeSerializable(); } //序列化 public static void testSerializable() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\test7.txt")); Person p = new Person(); p.name = "tom"; p.age = 12; oos.writeObject(p); oos.flush(); oos.close(); } //反序列化 public static void testDeSerializable() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\test7.txt")); Person p = null; Object obj = null; obj = ois.readObject(); p = (Person) obj; System.out.println(p.name); System.out.println(p.age); ois.close(); } }
七、RandomAccessFile
支持隨機(jī)訪(fǎng)問(wèn)的方式,程序可以直接跳轉(zhuǎn)到文件的任意位置地方來(lái)進(jìn)行讀寫(xiě)。支持只訪(fǎng)問(wèn)文件的部分內(nèi)容,可以向已存在的文件后追加內(nèi)容。
RandomAccessFile對(duì)象包含一個(gè)記錄指針,用以標(biāo)記當(dāng)前讀寫(xiě)的位置。
RandomAccessFile類(lèi)對(duì)象可以自由地移動(dòng)和記錄指針:
- long getFilePoint():獲取文件記錄指針的當(dāng)前位置;
- void seek(long pos):將文件記錄指針移動(dòng)到指定位置;
package anno; import java.io.IOException; import java.io.RandomAccessFile; public class Test9 { public static void main(String[] args) throws IOException { // testRandomAccessFileRead(); testRandomAccessFileWrite(); } public static void testRandomAccessFileRead() throws IOException { //構(gòu)造方法有兩個(gè)參數(shù),參數(shù)一為路徑,參數(shù)二為訪(fǎng)問(wèn)方式 //r:只讀 //rw:可寫(xiě)可讀 //rwd:可寫(xiě)可讀,同步內(nèi)容跟新 //rws:可寫(xiě)可讀,同步內(nèi)容和元數(shù)據(jù)跟新; RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","r"); //設(shè)置文件起始的讀取位置 acf.seek(5); byte[] b = new byte[35]; int len = 0; while((len=acf.read(b))!=-1) { System.out.println(new String(b, 0, len)); } acf.close(); } public static void testRandomAccessFileWrite() throws IOException { //構(gòu)造方法有兩個(gè)參數(shù),參數(shù)一為路徑,參數(shù)二為訪(fǎng)問(wèn)方式 //r:只讀 //rw:可寫(xiě)可讀 //rwd:可寫(xiě)可讀,同步內(nèi)容跟新 //rws:可寫(xiě)可讀,同步內(nèi)容和元數(shù)據(jù)跟新; RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","rw"); //設(shè)置文件起始的寫(xiě)入位置,0代表開(kāi)頭,acf.length代表文件末尾 acf.seek(acf.length()); acf.write("你好".getBytes()); acf.close(); } }
總結(jié):
流適用于處理數(shù)據(jù)的。
處理數(shù)據(jù)時(shí),一定要明確數(shù)據(jù)源,與數(shù)據(jù)目的地:數(shù)據(jù)源可以是文件,也可以是鍵盤(pán);數(shù)據(jù)目的地可以是文件、顯示器或其它設(shè)備。
流只是幫助數(shù)據(jù)進(jìn)行傳輸,并對(duì)傳輸?shù)臄?shù)據(jù)進(jìn)行處理,比如過(guò)濾處理、轉(zhuǎn)換處理等。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java中sleep方法和wait方法的五個(gè)區(qū)別
這篇文章主要介紹了java中sleep方法和wait方法的五個(gè)區(qū)別,sleep?方法和?wait?方法都是用來(lái)將線(xiàn)程進(jìn)入休眠狀態(tài),但是又有一些區(qū)別,下面我們就一起來(lái)看看吧2022-05-05MyBatis 三表外關(guān)聯(lián)查詢(xún)的實(shí)現(xiàn)(用戶(hù)、角色、權(quán)限)
這篇文章主要介紹了MyBatis 三表外關(guān)聯(lián)查詢(xún)的實(shí)現(xiàn)(用戶(hù)、角色、權(quán)限),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08IDEA報(bào)錯(cuò):Unable to save settings Failed to save settings
這篇文章主要介紹了IDEA報(bào)錯(cuò):Unable to save settings Failed to save settings的相關(guān)知識(shí),本文給大家分享問(wèn)題原因及解決方案,需要的朋友可以參考下2020-09-09SpringBoot如何實(shí)現(xiàn)定時(shí)任務(wù)示例詳解
使用定時(shí)任務(wù)完成一些業(yè)務(wù)邏輯,比如天氣接口的數(shù)據(jù)獲取,定時(shí)發(fā)送短信,郵件。以及商城中每天用戶(hù)的限額,定時(shí)自動(dòng)收貨等等,這篇文章主要給大家介紹了關(guān)于SpringBoot如何實(shí)現(xiàn)定時(shí)任務(wù)的相關(guān)資料,需要的朋友可以參考下2021-10-10SpringBoot集成Swagger2實(shí)現(xiàn)Restful(類(lèi)型轉(zhuǎn)換錯(cuò)誤解決辦法)
這篇文章主要介紹了SpringBoot集成Swagger2實(shí)現(xiàn)Restful(類(lèi)型轉(zhuǎn)換錯(cuò)誤解決辦法),需要的朋友可以參考下2017-07-07Java的MyBatis框架中關(guān)鍵的XML字段映射的配置參數(shù)詳解
將XML文件的schema字段映射到數(shù)據(jù)庫(kù)的schema是我們操作數(shù)據(jù)庫(kù)的常用手段,這里我們就來(lái)整理一些Java的MyBatis框架中關(guān)鍵的XML字段映射的配置參數(shù)詳解,需要的朋友可以參考下2016-06-06基于SpringBoot+Redis的Session共享與單點(diǎn)登錄詳解
這篇文章主要介紹了基于SpringBoot+Redis的Session共享與單點(diǎn)登錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07