java 写文件 0x0d_Java 读写文件 - My and My Princess…… - OSCHINA - 中文开源技术交流社区...
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* 對文本文件進行讀寫操作
*/
public class WriteAndReadText {
/**
* 文本文件所在的目錄
*/
private String textPath;
/**
* 讀取文本內容
* @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;
}
}
}
/**
* 將內容寫到文本中
* @param textname 文本名稱
* @param date 寫入的內容
* @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;
}
/**
* 在文檔后附加內容
* @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讀寫文件最常用的類是FileInputStream/FileOutputStream和FileReader/FileWriter。 其中FileInputStream和FileOutputStream是基于字節流的,常用于讀寫二進制文件。 讀寫字符文件建議使用基于字符的FileReader和FileWriter,省去了字節與字符之間的轉換。 但這兩個類的構造函數默認使用系統的編碼方式,如果文件內容與系統編碼方式不一致,可能會出現亂碼。 在這種情況下,建議使用FileReader和FileWriter的父類:InputStreamReader/OutputStreamWriter, 它們也是基于字符的,但在構造函數中可以指定編碼類型:InputStreamReader(InputStream in, Charset cs) 和OutputStreamWriter(OutputStream out, Charset cs)。 // 讀寫文件的編碼: InputStreamReader r = new InputStreamReader(new FileInputStream(fileName), “utf-8″); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),”utf-8″);
總結
以上是生活随笔為你收集整理的java 写文件 0x0d_Java 读写文件 - My and My Princess…… - OSCHINA - 中文开源技术交流社区...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java密钥库文件存在但为空_java安
- 下一篇: Java协作开发,Java开发学习笔记之