读文件和写文件小例子

/**
* 读取文本文件内容
*
* @param filePathAndName
* 带有完整绝对路径的文件名
* @param encoding
*            文本文件打开的编码方式
* @return 返回文本文件的内容
*/
public static String readTxt(String filePathAndName, String encoding)
throws IOException {
encoding = encoding.trim();
StringBuffer str = new StringBuffer("");
String st = "";
try {
FileInputStream fs = new FileInputStream(filePathAndName);
InputStreamReader isr;
if (encoding.equals("")) {
isr = new InputStreamReader(fs);
} else {
isr = new InputStreamReader(fs, encoding);
}
BufferedReader br = new BufferedReader(isr);
try {
String data = "";
while ((data = br.readLine()) != null) {
data = data.replace(data, "\r\n");
str.append(data + " ");
}
} catch (Exception e) {
str.append(e.toString());
}
st = str.toString();
} catch (IOException es) {
st = "";
}
return st;
}
/**
* 将文本内容写入文件
* @param fileName 带有完整绝对路径的文件名
* @param encoding 文本文件打开的编码方式
* @param towrite 文本内容
*/
public static void SaveStringToFile(String fileName, String towrite,String encoding) {
FileOutputStream fos = null;
OutputStreamWriter osw = null;

try {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
file = new File(fileName);
}
fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos, encoding);

osw.write(towrite);
osw.flush();
} catch (IOException iex) {
iex.printStackTrace();
} finally {
try {
if (null != osw)
osw.close();
if (null != fos)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值