您的位置:首页 > 其它

读文件和写文件小例子

2014-02-21 17:02 375 查看
/**

* 读取文本文件内容

*

* @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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: