java在文本区输出方法_Java文件的几种读取、输出方式
1、字節(jié)流----對(duì)文件讀取(速度慢)
/**
* 字節(jié)流---文件的讀取,輸出(缺點(diǎn):速度慢)
*
* @throws Exception
*/
@Test
public void testIO1() throws Exception {
// 輸入字節(jié)流對(duì)象
InputStream in = new FileInputStream("pkg/a.txt");
// 輸出字節(jié)流對(duì)象
OutputStream out = new FileOutputStream("pkg/b.txt");
//這里定義個(gè)字節(jié)數(shù)組,用來(lái)指定每次讀取的字節(jié)數(shù)
byte[] b = new byte[1024];
int len = -1;
while ((len = in.read(b, 0, b.length)) != -1) {
String str = new String(b, 0, len, "UTF-8");
System.out.println(str);
out.write(b, 0, len);
}
//關(guān)閉對(duì)象
out.close();
in.close();
}
2、帶緩存的字節(jié)流---文件讀取(速度快)
/**
* 緩存字節(jié)流---文件讀取,輸出(推薦:速度快)
*
* @throws Exception
*/
@Test
public void testIO2() throws Exception {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("pkg/a.txt"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("pkg/b.txt"));
byte[] b = new byte[1024];
int len = -1;
while ((len = in.read(b, 0, b.length)) != -1) {
String str = new String(b, 0, len, "UTF-8");
System.out.println(str);
out.write(b, 0, len);
}
//刷新緩沖
out.flush();
//關(guān)閉流對(duì)象
in.close();
out.close();
}
3、字節(jié)流reader,這個(gè)方法不能指定讀取的字節(jié)數(shù)(不推薦)
/*
* 字節(jié)流reader,不能指定字節(jié)長(zhǎng)度讀取,不建議使用
*/
@Test
public void testIO3() throws Exception {
InputStreamReader in = new InputStreamReader(new FileInputStream("pkg/a.txt"), "UTF-8");
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("pkg/b.txt"));
int len = -1;
while ((len = in.read()) != -1) {
System.out.println(len);
// 寫(xiě)入文件
out.write(len);
}
out.flush();
in.close();
out.close();
}
4、帶緩沖的字節(jié)流讀取方式,readLine()
/**
* 另一種字節(jié)流讀取方式----可以提供readLine()的方法,一次讀取一行。
*
* @throws Exception
*/
@Test
public void testIO4() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("pkg/a.txt"), "UTF-8"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("pkg/b.txt"), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
out.write(str + "\n");
}
out.flush();
in.close();
out.close();
}
小結(jié):實(shí)際在用的過(guò)程,肯定是選擇帶有緩沖區(qū)的字節(jié)流讀取方式,另外能夠指定每次讀取的字節(jié)數(shù)最好不過(guò)了。因此,方式2 推薦使用。
總結(jié)
以上是生活随笔為你收集整理的java在文本区输出方法_Java文件的几种读取、输出方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: oracle java 绑定变量的值_O
- 下一篇: java 查询启动时间_java获取系统