java读写文件


package velcro.util;

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″);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值