您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何在java中使用數據流,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
一、不帶緩沖的流
1.文件字節輸入流、文件字節輸出流
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); //設置一個數組接收文件的內容 //需要注意的是,如果數組設置的太小,那么可能出現讀取的數據不完整或者亂碼等情況 byte[] b = new byte[30]; //文件輸入流對象有一個返回值,返回的是讀取數據的長度,如果讀取到一個數據了,還會向后讀一個, //當讀取完畢時會返回-1 int len = 0; while((len=fs.read(b))!=-1) { //參數1是緩沖數據數組,參數2是從哪個位置開始轉換成字符串,參數3是總共轉換的長度 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]; //將讀取的數據存入到b中 fs.read(b); //將b轉換成字符串并輸出 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() { //如果不存在該文件,則系統會新建一個 String path2 = "F:\\test2.txt"; try { FileOutputStream fo = new FileOutputStream(path2); String str = "這是我測試的輸入"; fo.write(str.getBytes());//將數據寫到byte中 fo.flush();//將內存中的數據寫到文件中 fo.close();//關閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
在運行的過程中會遇到一些問題,比如說設置的byte數組來接收讀取的數據,如果初始化長度給的比較小,那么讀取的數據就不全,在進行test1FileInputStream()的實驗中,即使按照:
int len = 0; while((len=fs.read(b))!=-1) { //參數1是緩沖數據數組,參數2是從哪個位置開始轉換成字符串,參數3是總共轉換的長度 System.out.println(new String(b, 0, len)); }
進行輸出,如果byte設置的還是太小,就會出現:
這是我新建的test.txt?
??件
這種亂碼問題,于是進行了第二種方法的嘗試,即在傳入數據之前首先獲得要接收多少字節的數據,然后在進行接收(借鑒之前在golang中文件讀取并顯示的思想),然后就沒有問題了,即test2FileInputStream()。
輸出結果:
這是我新建的test.txt文件
2.使用字節流將一個文件復制到指定的文件夾下
public static void copyFile() { String path = "F:\\test.txt"; String path3 = "F:\\test2.txt"; try { FileInputStream fi = new FileInputStream(path); FileOutputStream fo = new FileOutputStream(path3); 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類型的數組了 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 path2 = "F:\\test2.txt"; try { FileWriter fw = new FileWriter(path2); String str = "這是我測試的輸入"; //注意這里可以直接寫入字符串 fw.write(str); fw.flush();//將內存中的數據寫到文件中 fw.close();//關閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
需要注意的是定義char數組時仍然是需要知道數據是有多少字符的,不然長度不夠,顯示不全或者寫入不全。(這里暫時還未了解怎么處理)
4.使用字符流將一個文件復制到指定的文件夾下
public static void copyFile2() { String path = "F:\\test.txt"; String path3 = "F:\\test2.txt"; try { FileReader fr = new FileReader(path); FileWriter fw = new FileWriter(path3); 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(); } }
二、帶緩沖的流
為了提高數據的讀寫速度,java API提供了帶緩沖功能的流類,在使用這些流類時,會創建一個內部緩沖區數組。
根據數據操作單位可以把緩沖流分為:BufferedInputStream/BufferedOutputStream和BufferedReader/BufferedWriter。
緩沖流要“套接”在相應的節點流之上,對讀寫的數據提供了緩沖的功能,提高了讀寫的效率,同時增加了些新方法。對于輸出的緩沖流,寫出的數據都會先在內存中緩存,使用flush()會將在內存中的數據立即寫出。
1.緩沖字節輸入流、緩沖字節輸出流
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"); //把文件字節輸入流放入到緩沖輸入流中 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"); //把文件字節輸入流放入到緩沖輸入流中 BufferedOutputStream bo = new BufferedOutputStream(fo); String str = "這是我測試的內容"; bo.write(str.getBytes()); bo.flush(); bo.close(); fo.close(); } public static void copyFile() { String path = "F:\\test.txt"; String path3 = "F:\\test2.txt"; try { FileInputStream fi = new FileInputStream(path); BufferedInputStream bi = new BufferedInputStream(fi); FileOutputStream fo = new FileOutputStream(path3); 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 path2 = "F:\\test2.txt"; try { FileWriter fw = new FileWriter(path2); BufferedWriter bw = new BufferedWriter(fw); String str = "這是我測試的輸入"; bw.write(str);//將數據寫到chars中 bw.flush();//將內存中的數據寫到文件中 bw.close(); fw.close();//關閉 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copyFile() { String path = "F:\\test.txt"; String path3 = "F:\\test2.txt"; try { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(path3); 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(); } } }
三、轉換流:用于字節流和字符流之間的轉換
java Api提供了兩個轉換流:InputStreamReader和OutputSreamWriter。
當字節流中的數據都是字符時,轉換成字符流操作更高效
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"); //字節流轉換成字符流 //注意轉換成的編碼要和讀取的文件一致 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"); //轉換字節輸出流為字符輸出流 OutputStreamWriter ow = new OutputStreamWriter(fo,"utf-8"); String str = "這是我測試的內容"; ow.write(str); ow.flush(); ow.close(); fo.close(); } public static void copyFile() { String path = "F:\\test.txt"; String path3 = "F:\\test2.txt"; try { FileInputStream fi = new FileInputStream(path); BufferedInputStream bi = new BufferedInputStream(fi); FileOutputStream fo = new FileOutputStream(path3); 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(); } } }
四、標準輸入輸出流
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 { //創建一個獲取鍵盤輸入的輸入流 InputStreamReader ir = new InputStreamReader(System.in); //將輸入流放在緩沖中 BufferedReader br = new BufferedReader(ir); String str = ""; while((str = br.readLine())!=null) { System.out.println(str); } } //將控制臺的輸入寫入到txt文件中 public static void testWriterToTxt() throws IOException { //創建一個獲取鍵盤輸入的輸入流 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(); } }
五、數據流
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(); } //用數據輸出流寫到文件中的基本類型數據是亂碼,不能辨認出來,需要數據輸入流讀取 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(); } }
六、對象流
用于存儲和讀取對象的處理流,它的強大之處就是可以把java中對象寫入到數據源中,也能把對象從數據源中還原出來。
序列化:用ObjectOutputStream類將一個對象下入io流中;
反序列化:用ObjectInputStream類從io流中恢復對Java對象;
package anno; import java.io.Serializable; public class Person implements Serializable{ //用來標識的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
支持隨機訪問的方式,程序可以直接跳轉到文件的任意位置地方來進行讀寫。支持只訪問文件的部分內容,可以向已存在的文件后追加內容。
RandomAccessFile對象包含一個記錄指針,用以標記當前讀寫的位置。
RandomAccessFile類對象可以自由地移動和記錄指針:
long getFilePoint():獲取文件記錄指針的當前位置;
void seek(long pos):將文件記錄指針移動到指定位置;
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 { //構造方法有兩個參數,參數一為路徑,參數二為訪問方式 //r:只讀 //rw:可寫可讀 //rwd:可寫可讀,同步內容跟新 //rws:可寫可讀,同步內容和元數據跟新; RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","r"); //設置文件起始的讀取位置 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 { //構造方法有兩個參數,參數一為路徑,參數二為訪問方式 //r:只讀 //rw:可寫可讀 //rwd:可寫可讀,同步內容跟新 //rws:可寫可讀,同步內容和元數據跟新; RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","rw"); //設置文件起始的寫入位置,0代表開頭,acf.length代表文件末尾 acf.seek(acf.length()); acf.write("你好".getBytes()); acf.close(); } }
上述內容就是如何在java中使用數據流,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。