Java讀文件寫(xiě)文件操作(續(xù))
2
3 import java.io.File;
4 import java.io.FileWriter;
5 import java.io.IOException;
6
7 /**
8 * 對(duì)文本文件進(jìn)行讀寫(xiě)操作
9 */
10 public class WriteAndReadText {
11 /**
12 * 文本文件所在的目錄
13 */
14 private String textPath;
15 /**
16 * 讀取文本內(nèi)容
17 * @param textname 文本名稱
18 * @return
19 */
20 public String readText(String textname){
21 File file=new File(textPath+File.separator+textname);
22 try {
23 BufferedReader br = new BufferedReader(new java.io.FileReader(file));
24 StringBuffer sb = new StringBuffer();
25 String line = br.readLine();
26 while (line != null) {
27 sb.append(line);
28 line = br.readLine();
29 }
30 br.close();
31 return sb.toString();
32 } catch (IOException e) {
33 LogInfo.error(this.getClass().getName(),e.getLocalizedMessage(),e);
34 e.printStackTrace();
35 return null;
36 }
37 }
38 }
39 /**
40 * 將內(nèi)容寫(xiě)到文本中
41 * @param textname 文本名稱
42 * @param date 寫(xiě)入的內(nèi)容
43 * @return
44 */
45 public boolean writeText(String textname,String date){
46 boolean flag=false;
47 File filePath=new File(textPath);
48 if(!filePath.exists()){
49 filePath.mkdirs();
50 }
51 try {
52 FileWriter fw =new FileWriter(textPath+File.separator+textname);
53 fw.write(date);
54 flag=true;
55 if(fw!=null)
56 fw.close();
57 } catch (IOException e) {
58 LogInfo.error(this.getClass().getName(),e.getMessage(),e);
59 e.printStackTrace();
60 }
61
62 return flag;
63 }
64 /**
65 * 在文檔后附加內(nèi)容
66 * @param textName
67 * @param date
68 * @return
69 */
70 public boolean appendText(String textName,String date){
71 boolean flag=false;
72 File filePath=new File(textPath);
73 if(!filePath.exists()){
74 filePath.mkdirs();
75 }
76 try {
77 FileWriter fw =new FileWriter(textPath+File.separator+textName,true);
78 fw.append(date);
79 flag=true;
80 if(fw!=null)
81 fw.close();
82 } catch (IOException e) {
83 LogInfo.error(this.getClass().getName(),e.fillInStackTrace().toString());
84 e.printStackTrace();
85 }
86 return flag;
87 }
88 public String getTextPath() {
89 return textPath;
90 }
91 public void setTextPath(String textPath) {
92 this.textPath = textPath;
93 }
94 }
95
PrintWriter out = new PrintWriter(new FileWriter(logFileName, true), true);
Java讀寫(xiě)文件最常用的類是FileInputStream/FileOutputStream和FileReader/FileWriter。
其中FileInputStream和FileOutputStream是基于字節(jié)流的,常用于讀寫(xiě)二進(jìn)制文件。
讀寫(xiě)字符文件建議使用基于字符的FileReader和FileWriter,省去了字節(jié)與字符之間的轉(zhuǎn)換。
但這兩個(gè)類的構(gòu)造函數(shù)默認(rèn)使用系統(tǒng)的編碼方式,如果文件內(nèi)容與系統(tǒng)編碼方式不一致,可能會(huì)出現(xiàn)亂碼。
在這種情況下,建議使用FileReader和FileWriter的父類:InputStreamReader/OutputStreamWriter,
它們也是基于字符的,但在構(gòu)造函數(shù)中可以指定編碼類型:InputStreamReader(InputStream in, Charset cs) 和OutputStreamWriter(OutputStream out, Charset cs)。
// 讀寫(xiě)文件的編碼:
InputStreamReader r = new InputStreamReader(new FileInputStream(fileName), “utf-8″);
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),”utf-8″);
posted on 2009-07-17 22:16 彭偉 閱讀(930) 評(píng)論(0) 編輯 收藏 所屬分類: java技術(shù)分區(qū)