Java文件(io)編程之文件字符流使用方法詳解
本文實例為大家分享了文件字符流的使用方法,供大家參考,具體內(nèi)容如下
案例1:
讀取一個文件并寫入到另一個文件中,char[] 來中轉(zhuǎn)。
首先要在E盤下創(chuàng)建一個文本文檔,命名為test.txt,輸入一些字符串。
public class Demo_5 {
public static void main(String[] args) {
FileReader fr=null; //文件取出字符流對象(輸入流)
FileWriter fw=null; //寫入到文件(輸出流)
try {
fr=new FileReader("e:\\test.txt"); //創(chuàng)建一個fr對象
fw=new FileWriter("d:\\test.txt"); //創(chuàng)建輸出對象
char []c=new char[1024]; //讀入到內(nèi)存
int n=0; //記錄實際讀取到的字符數(shù)
while((n=fr.read(c))!=-1){
//String s=new String(c,0,n);
fw.write(c,0,n);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fr.close();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
打開D盤的test.txt文件,出現(xiàn)相同的字符串。
案例2:為了提高效率引入了緩沖字符流
依然實現(xiàn)讀取一個文件并寫入到另一個文件中,直接操作String。
public class Demo_6 {
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
try{
FileReader fr=new FileReader("e:\\test.txt"); //先創(chuàng)建FileReader對象
br=new BufferedReader(fr);
FileWriter fw=new FileWriter("d:\\test1.txt"); //創(chuàng)建FileWriter對象
bw=new BufferedWriter(fw);
String s="";
while((s=br.readLine())!=null){ //循環(huán)讀取文件,s不為空即還未讀完畢
bw.write(s+"\r\n"); //輸出到磁盤,加上“\r\n”為了實現(xiàn)換行
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
br.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
打開D盤的test1.txt文件,出現(xiàn)相同的字符串。
總結(jié):字節(jié)流操作對象byte,字符流操作對象char,緩沖字符流操作對象String。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis分頁插件PageHelper手寫實現(xiàn)示例
這篇文章主要為大家介紹了Mybatis分頁插件PageHelper手寫實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
Elasticsearch term 查詢之精確值搜索功能實現(xiàn)
term查詢是Elasticsearch中用于精確值搜索的一種基本方式,通過了解 term 查詢的工作原理和使用方法,你可以更好地利用 Elasticsearch 進行結(jié)構(gòu)化數(shù)據(jù)的搜索和分析,本文將詳細(xì)介紹 term 查詢的工作原理、使用場景以及如何在 Elasticsearch 中應(yīng)用它,感興趣的朋友一起看看吧2024-06-06

