java常用數(shù)據(jù)流應(yīng)用實例解析
這篇文章主要介紹了java常用數(shù)據(jù)流應(yīng)用實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
按操作單位的不同分為:字節(jié)流(8bit)(InputStream、OuputStream)、字符流(16bit)(Reader、Writer)
按數(shù)據(jù)流的流向不同分為:輸入流、輸出流
按角色的不同分為:節(jié)點流、處理流
一、不帶緩沖的流
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è)置一個數(shù)組接收文件的內(nèi)容
//需要注意的是,如果數(shù)組設(shè)置的太小,那么可能出現(xiàn)讀取的數(shù)據(jù)不完整或者亂碼等情況
byte[] b = new byte[30];
//文件輸入流對象有一個返回值,返回的是讀取數(shù)據(jù)的長度,如果讀取到一個數(shù)據(jù)了,還會向后讀一個,
//當讀取完畢時會返回-1
int len = 0;
while((len=fs.read(b))!=-1) {
//參數(shù)1是緩沖數(shù)據(jù)數(shù)組,參數(shù)2是從哪個位置開始轉(zhuǎn)換成字符串,參數(shù)3是總共轉(zhuǎn)換的長度
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)會新建一個
String path1 = "F:\\test2.txt";
try {
FileOutputStream fo = new FileOutputStream(path1);
String str = "這是我測試的輸入";
fo.write(str.getBytes());//將數(shù)據(jù)寫到byte中
fo.flush();//將內(nèi)存中的數(shù)據(jù)寫到文件中
fo.close();//關(guān)閉
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在運行的過程中會遇到一些問題,比如說設(shè)置的byte數(shù)組來接收讀取的數(shù)據(jù),如果初始化長度給的比較小,那么讀取的數(shù)據(jù)就不全,在進行test1FileInputStream()的實驗中,即使按照:
int len = 0;
while((len=fs.read(b))!=-1) {
//參數(shù)1是緩沖數(shù)據(jù)數(shù)組,參數(shù)2是從哪個位置開始轉(zhuǎn)換成字符串,參數(shù)3是總共轉(zhuǎn)換的長度
System.out.println(new String(b, 0, len));
}
進行輸出,如果byte設(shè)置的還是太小,就會出現(xiàn):
這是我新建的test.txt�
��件
這種亂碼問題,于是進行了第二種方法的嘗試,即在傳入數(shù)據(jù)之前首先獲得要接收多少字節(jié)的數(shù)據(jù),然后在進行接收(借鑒之前在golang中文件讀取并顯示的思想),然后就沒有問題了,即test2FileInputStream()。
輸出結(jié)果:
這是我新建的test.txt文件
2.使用字節(jié)流將一個文件復(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類型的數(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 = "這是我測試的輸入";
//注意這里可以直接寫入字符串
fw.write(str);
fw.flush();//將內(nèi)存中的數(shù)據(jù)寫到文件中
fw.close();//關(guān)閉
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
需要注意的是定義char數(shù)組時仍然是需要知道數(shù)據(jù)是有多少字符的,不然長度不夠,顯示不全或者寫入不全。(這里暫時還未了解怎么處理)
4.使用字符流將一個文件復(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ù)的讀寫速度,java API提供了帶緩沖功能的流類,在使用這些流類時,會創(chuàng)建一個內(nèi)部緩沖區(qū)數(shù)組。
根據(jù)數(shù)據(jù)操作單位可以把緩沖流分為:BufferedInputStream/BufferedOutputStream和BufferedReader/BufferedWriter。
緩沖流要“套接”在相應(yīng)的節(jié)點流之上,對讀寫的數(shù)據(jù)提供了緩沖的功能,提高了讀寫的效率,同時增加了些新方法。對于輸出的緩沖流,寫出的數(shù)據(jù)都會先在內(nèi)存中緩存,使用flush()會將在內(nèi)存中的數(shù)據(jù)立即寫出。
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 = "這是我測試的內(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 = "這是我測試的輸入";
bw.write(str);//將數(shù)據(jù)寫到chars中
bw.flush();//將內(nèi)存中的數(shù)據(jù)寫到文件中
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提供了兩個轉(zhuǎn)換流:InputStreamReader和OutputSreamWriter。
當字節(jié)流中的數(shù)據(jù)都是字符時,轉(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 = "這是我測試的內(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();
}
}
}
四、標準輸入輸出流
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)建一個獲取鍵盤輸入的輸入流
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 {
//創(chuàng)建一個獲取鍵盤輸入的輸入流
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ù)輸出流寫到文件中的基本類型數(shù)據(jù)是亂碼,不能辨認出來,需要數(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();
}
}
六、對象流
用于存儲和讀取對象的處理流,它的強大之處就是可以把java中對象寫入到數(shù)據(jù)源中,也能把對象從數(shù)據(jù)源中還原出來。
序列化:用ObjectOutputStream類將一個對象下入io流中;
反序列化:用ObjectInputStream類從io流中恢復(fù)對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
支持隨機訪問的方式,程序可以直接跳轉(zhuǎn)到文件的任意位置地方來進行讀寫。支持只訪問文件的部分內(nèi)容,可以向已存在的文件后追加內(nèi)容。
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 {
//構(gòu)造方法有兩個參數(shù),參數(shù)一為路徑,參數(shù)二為訪問方式
//r:只讀
//rw:可寫可讀
//rwd:可寫可讀,同步內(nèi)容跟新
//rws:可寫可讀,同步內(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)造方法有兩個參數(shù),參數(shù)一為路徑,參數(shù)二為訪問方式
//r:只讀
//rw:可寫可讀
//rwd:可寫可讀,同步內(nèi)容跟新
//rws:可寫可讀,同步內(nèi)容和元數(shù)據(jù)跟新;
RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","rw");
//設(shè)置文件起始的寫入位置,0代表開頭,acf.length代表文件末尾
acf.seek(acf.length());
acf.write("你好".getBytes());
acf.close();
}
}
總結(jié):
流適用于處理數(shù)據(jù)的。
處理數(shù)據(jù)時,一定要明確數(shù)據(jù)源,與數(shù)據(jù)目的地:數(shù)據(jù)源可以是文件,也可以是鍵盤;數(shù)據(jù)目的地可以是文件、顯示器或其它設(shè)備。
流只是幫助數(shù)據(jù)進行傳輸,并對傳輸?shù)臄?shù)據(jù)進行處理,比如過濾處理、轉(zhuǎn)換處理等。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持我們。
上一篇:為什么SpringMVC中請求的body不支持多次讀取
欄 目:Java
下一篇:JAVA8 STREAM COLLECT GROUPBY分組實例解析
本文標題:java常用數(shù)據(jù)流應(yīng)用實例解析
本文地址:http://www.jygsgssxh.com/a1/Java/8786.html
您可能感興趣的文章
- 01-10Java實現(xiàn)動態(tài)模擬時鐘
- 01-10利用Java實現(xiàn)復(fù)制Excel工作表功能
- 01-10JavaWeb實現(xiàn)郵件發(fā)送功能
- 01-10java基于poi導出excel透視表代碼實例
- 01-10Java實現(xiàn)動態(tài)數(shù)字時鐘
- 01-10基于Java驗證jwt token代碼實例
- 01-10java實現(xiàn)液晶數(shù)字字體顯示當前時間
- 01-10淺談Java中真的只有值傳遞么
- 01-10Java動態(tài)顯示當前日期和時間
- 01-10如何解決線程太多導致java socket連接池出現(xiàn)的問題


閱讀排行
本欄相關(guān)
- 01-10Java實現(xiàn)動態(tài)模擬時鐘
- 01-10Springboot中@Value的使用詳解
- 01-10JavaWeb實現(xiàn)郵件發(fā)送功能
- 01-10利用Java實現(xiàn)復(fù)制Excel工作表功能
- 01-10Java實現(xiàn)動態(tài)數(shù)字時鐘
- 01-10java基于poi導出excel透視表代碼實例
- 01-10java實現(xiàn)液晶數(shù)字字體顯示當前時間
- 01-10基于Java驗證jwt token代碼實例
- 01-10Java動態(tài)顯示當前日期和時間
- 01-10淺談Java中真的只有值傳遞么
隨機閱讀
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10C#中split用法實例總結(jié)
- 04-02jquery與jsp,用jquery
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10delphi制作wav文件的方法
- 01-10使用C語言求解撲克牌的順子及n個骰子


