所天用到了java里的讀寫文件操作,查了一些資料,發現不論是讀文件還是寫文件都有三種不同的方式:我想請教各位高手三種方式各有什么優缺點,先謝謝各位了。
讀操作三種方式:
1 : BufferReader
2 : FileReader
3 : InputStreamReader
寫文件得三種方式:
1 :PrintWriter
2 :FileWriter
3 :OutputStreamWriter
以下是測試用得代碼:
/***********************************************************
*2007-9-17
*Blw.beans
*DManagement
*MagicBlw
***********************************************************/
package test;

import java.io.BufferedReader;
import java.io.*;


public class MakeJsp {

/**
* @param args
*/
//定義生產文件名稱
private String name="moban";
private String houzhui=".html";
//定義所查看文件的路徑
private String addresspath="d://2.html";
private String addresspath1="D://top.html";
private String neirong="姓名";
public static void main(String[] args) {
MakeJsp w=new MakeJsp();
w.getFile();
}
public void getFile()
{
File file1= new File(addresspath);

//要寫進去的內容
String s ="000000000000000000000"+neirong;
String s1="111111111111111111111"+neirong;
String s2="222222222222222222222"+neirong;
String s3="<html><body>blw=="+neirong+"</body></html>";
PrintWriter pw=null;
BufferedReader br=null;
OutputStreamWriter ow=null;
FileWriter fw=null;
FileReader fr=null;
InputStreamReader isr =null;
try {
//創建文件
file1.createNewFile();
/*
* 讀文件的三種方式:
*/
//讀文件方式一:
br=new BufferedReader(new InputStreamReader(new FileInputStream(addresspath1)));
String data=null;
while((data=br.readLine())!=null)
{
//data=(new String(data.getBytes("ISO-8859-1"),"GB2312")).trim();
System.out.println(data);
}

//讀文件方式二:
fr = new FileReader(addresspath1);
int ch=0;
while((ch=fr.read())!=-1)
{
//FileReader方式是通過讀取單個字符實現的 所以用 System.out.print
System.out.print((char)ch);
}
//讀文件方式三
isr = new InputStreamReader(new FileInputStream(addresspath1));
int ch1=0;
while((ch1=isr.read())!=-1)
{
//InputStreamReader方式是通過讀取單個字符實現的 所以用 System.out.print
System.out.print((char)ch1);
}
/*
* java寫文件的三種方式
*/
//方式一
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(addresspath)),true);
pw.println(s);
//方式二:
fw =new FileWriter(addresspath);
fw.write(s1, 0, s1.length());
fw.flush();
//方式三:
ow =new OutputStreamWriter(new FileOutputStream(addresspath));
ow.write(s3, 0, s3.length());
ow.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//關閉資源
try {
pw.close();
br.close();
ow.close();
fw.close();
fr.close();
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("關閉文件資源失敗");
}
}
}

}
核心: 勇敢進取年輕的心
讀操作三種方式:
1 : BufferReader
2 : FileReader
3 : InputStreamReader
寫文件得三種方式:
1 :PrintWriter
2 :FileWriter
3 :OutputStreamWriter
以下是測試用得代碼:








































































































































核心: 勇敢進取年輕的心