java 写文件 0x0d_Java 读写文件 - My and My Princess…… - OSCHINA - 中文开源技术交流社区...
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* 對(duì)文本文件進(jìn)行讀寫(xiě)操作
*/
public class WriteAndReadText {
/**
* 文本文件所在的目錄
*/
private String textPath;
/**
* 讀取文本內(nèi)容
* @param textname 文本名稱
* @return
*/
public String readText(String textname){
File file=new File(textPath+File.separator+textname);
try {
BufferedReader br = new BufferedReader(new java.io.FileReader(file));
StringBuffer sb = new StringBuffer();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
br.close();
return sb.toString();
} catch (IOException e) {
LogInfo.error(this.getClass().getName(),e.getLocalizedMessage(),e);
e.printStackTrace();
return null;
}
}
}
/**
* 將內(nèi)容寫(xiě)到文本中
* @param textname 文本名稱
* @param date 寫(xiě)入的內(nèi)容
* @return
*/
public boolean writeText(String textname,String date){
boolean flag=false;
File filePath=new File(textPath);
if(!filePath.exists()){
filePath.mkdirs();
}
try {
FileWriter fw =new FileWriter(textPath+File.separator+textname);
fw.write(date);
flag=true;
if(fw!=null)
fw.close();
} catch (IOException e) {
LogInfo.error(this.getClass().getName(),e.getMessage(),e);
e.printStackTrace();
}
return flag;
}
/**
* 在文檔后附加內(nèi)容
* @param textName
* @param date
* @return
*/
public boolean appendText(String textName,String date){
boolean flag=false;
File filePath=new File(textPath);
if(!filePath.exists()){
filePath.mkdirs();
}
try {
FileWriter fw =new FileWriter(textPath+File.separator+textName,true);
fw.append(date);
flag=true;
if(fw!=null)
fw.close();
} catch (IOException e) {
LogInfo.error(this.getClass().getName(),e.fillInStackTrace().toString());
e.printStackTrace();
}
return flag;
}
public String getTextPath() {
return textPath;
}
public void setTextPath(String textPath) {
this.textPath = textPath;
}
}
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″);
總結(jié)
以上是生活随笔為你收集整理的java 写文件 0x0d_Java 读写文件 - My and My Princess…… - OSCHINA - 中文开源技术交流社区...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java密钥库文件存在但为空_java安
- 下一篇: Java协作开发,Java开发学习笔记之