Servlet中操作文件详解及实例
因为Servlet本来就是一个.Java文件,因此servlet中操作文件和普通java文件操作文件是一样的。
读取文件主要代码:
FileReader f=new FileReader("f:\\lissdy.txt");
BufferedReader bw=new BufferedReader(f);
读出一行数据
String num=bw.readLine();
注意一定要关闭文件流
写文件的方法与之类似,具体代码为:
读取:
package com.lissdy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@SuppressWarnings("serial")
public class ReadFile extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try {
res.setContentType("text/html;charset=gbk");
PrintWriter pw=res.getWriter();
FileReader f=new FileReader("d:\\lissdy.txt");
BufferedReader bw=new BufferedReader(f);
String num=bw.readLine();
bw.close();
pw.println("从文件中读取的数据是:"+num);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
写入:
package com.lissdy;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@SuppressWarnings("serial")
public class WriteFile extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try {
res.setContentType("text/html;charset=gbk");
PrintWriter pw=res.getWriter();
//从内存到磁盘流动为写(输出流)
//从磁盘文件到内存流动为读(输入流)
FileWriter f=new FileWriter("d:\\lissdy.txt");
BufferedWriter bw=new BufferedWriter(f);
bw.write("试一试文件怎么写");
pw.println("向文件写入数据");
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!