将外部文件读取成为字符串
public String doPageToStr(String filename) {
StringBuffer buf = new StringBuffer();
BufferedReader breader = null;
try {
breader = new BufferedReader(
new FileReader(filename));
while (breader.ready()) {
buf.append((char) breader.read());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (breader != null) {
try {
breader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buf.toString();
}
将字符串存储为文件
public void doTask(String strPage, String basePath, ProductDownload product) {
synchronized (lock) {
String text = strPage;
String path = basePath;
String filePath = path + File.separator + "product"
+ product.getProductId() + File.separator + "product.html";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fos));
bw.write(text);
bw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
}
}
}
本文介绍了如何使用Java代码将外部文件读取为字符串,并将其存储到指定路径的文件中。重点阐述了BufferedReader与FileOutputStream的使用方法,以及异常处理与资源释放。

被折叠的 条评论
为什么被折叠?



