1 回答

TA貢獻1875條經(jīng)驗 獲得超3個贊
首先你要知道java的io流主要分兩種,一種是字符流,另一種字節(jié)流,還有一種過濾流,這個不常用,暫且可以忽略。
等你這些都掌握了,推薦你用nio包中的管道流。
流的套用可以提升讀寫效率(這種方式只能是同類流的套用,比如字節(jié)流套用字節(jié)流),還有一種是字符流與字節(jié)流互相轉換,轉換通過一種叫做“橋轉換”的類,比如OutputStreamWriter類。
下面舉個最基礎的字節(jié)流例子:
public void copyFile(String file, String bak) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
byte[] bytes = new byte[1024];
bis = new BufferedInputStream(new FileInputStream(file));//BufferedInputStream會構造一個背部緩沖區(qū)數(shù)組,將FileInputStream中的數(shù)據(jù)存放在緩沖區(qū)中,提升了讀取的性能
bos = new BufferedOutputStream(new FileOutputStream(bak));//同理
int length = bis.read(bytes);
while (length != -1) {
System.out.println("length: " + length);
bos.write(bytes, 0, length);
length = bis.read(bytes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
字符流的用法:
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader br = new BufferedReader(fr);
或者PrintWriter pw = new PrintWriter(new FileWriter("D:\\test.txt"));
和這個有點類似
- 1 回答
- 0 關注
- 191 瀏覽
添加回答
舉報