import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
//写入文件
public void writeToFile(File file, String context, boolean isAppend)
throws IOException {
BufferedWriter bw = null;
if (file.exists()) {
file.createNewFile();
file = new File(file.getPath());
}
FileWriter fw = new FileWriter(file, isAppend);
bw = new BufferedWriter(fw);
fw.write(context);
fw.flush();
fw.close();
}
//读取文件内容
public void readToBuffer(StringBuffer buffer, InputStream is)
throws IOException {
String line; // 用来保存每行读取的内容
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine(); // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("/n"); // 添加换行符
line = reader.readLine(); // 读取下一行
}
}
public String getAll() {
File file = new File(ServletActionContext.getServletContext()
.getRealPath("test.txt"));
// ---写入
try {
this.writeToFile(file, "a:a<br /> b:b<br /> c:c<br /> ", false);
this.writeToFile(file, "a:AAAAA<br /> b:BBB", true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// ---读取
InputStream is = null;
try {
is = new FileInputStream(file.getPath());
StringBuffer buffer = new StringBuffer();
this.readToBuffer(buffer, is);
response.getWriter().println(buffer.toString());
request.setAttribute("text", buffer.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return SUCCESS;
}
说明:部分内容来自网友提供