两个关于txt文件读写的方法,以供学习交流!
方法一:
/**
* 采用BufferedReader读取文本文件p
* @return
*/
public String ReadTxt1(){
String url = "D:/text/1.txt";
StringBuffer strb = new StringBuffer();
try {
FileInputStream fs = new FileInputStream(new File(url));
InputStreamReader isr = new InputStreamReader(fs);
BufferedReader br = new BufferedReader(isr);
String data = "";
while((data = br.readLine()) != null){
strb.append(data + " ");
}
br.close();
System.out.println(strb.toString());
return strb.toString();
} catch (Exception e) {
System.out.println("读取失败!");
e.printStackTrace();
return null;
}
}
方法二:
/**
* 采用FileReader(字符串形式)读取文本文件p
* @return
*/
public String ReadTxt2(){
String url = "D:/text/1.txt";
String strs = "";
try {
FileReader fread = new FileReader(new File(url));
StringBuffer strb = new StringBuffer();
char ch[] = new char[1024];
int re = fread.read(ch);
while(re != -1){
String str = new String(ch,0,re);
strb.append(str);
re = fread.read(ch);
}
System.out.println(strb.toString());
return strb.toString();
} catch (Exception e) {
System.out.println("读取失败!");
e.printStackTrace();
return null;
}
}