java實(shí)現(xiàn)讀寫(xiě)文件操作的三種不同方式
Posted on 2007-09-18 10:13 怎么羨慕天空的飛鳥(niǎo) 閱讀(2614) 評(píng)論(1) 編輯 收藏 所天用到了java里的讀寫(xiě)文件操作,查了一些資料,發(fā)現(xiàn)不論是讀文件還是寫(xiě)文件都有三種不同的方式:我想請(qǐng)教各位高手三種方式各有什么優(yōu)缺點(diǎn),先謝謝各位了。
讀操作三種方式:
1 : BufferReader
2 : FileReader
3 : InputStreamReader
寫(xiě)文件得三種方式:
1 :PrintWriter
2 :FileWriter
3 :OutputStreamWriter
以下是測(cè)試用得代碼:
/***********************************************************
*2007-9-17
*Blw.beans
*DManagement
*MagicBlw
***********************************************************/
package test;

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


public class MakeJsp {

/**
* @param args
*/
//定義生產(chǎn)文件名稱(chēng)
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);

//要寫(xiě)進(jìn)去的內(nèi)容
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 {
//創(chuàng)建文件
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方式是通過(guò)讀取單個(gè)字符實(shí)現(xiàn)的 所以用 System.out.print
System.out.print((char)ch);
}
//讀文件方式三
isr = new InputStreamReader(new FileInputStream(addresspath1));
int ch1=0;
while((ch1=isr.read())!=-1)
{
//InputStreamReader方式是通過(guò)讀取單個(gè)字符實(shí)現(xiàn)的 所以用 System.out.print
System.out.print((char)ch1);
}
/*
* java寫(xiě)文件的三種方式
*/
//方式一
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
{
//關(guān)閉資源
try {
pw.close();
br.close();
ow.close();
fw.close();
fr.close();
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("關(guān)閉文件資源失敗");
}
}
}

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








































































































































核心: 勇敢進(jìn)取年輕的心