servlet 上传文本文件并读取文件内容
public class test extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
try {
if(ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory dff=new DiskFileItemFactory();// 创建该对象
dff.setSizeThreshold(1024000);// 指定在内存中缓存数据大小,单位为byte
ServletFileUpload sfu=new ServletFileUpload(dff);// 创建该对象
sfu.setFileSizeMax(5000000);// 指定单个上传文件的最大尺寸
sfu.setSizeMax(10000000);// 指定一次上传多个文件的 总尺寸
FileItemIterator fii=sfu.getItemIterator(request);// 解析request 请求,并返回FileItemIterator集合
StringBuffer stringBuffer=new StringBuffer();
while(fii.hasNext()) {
FileItemStream fis=fii.next();// 从集合中获得一个文件流
if(!fis.isFormField() && fis.getName().length() > 0) {// 过滤掉表单中非文件
BufferedInputStream in=new BufferedInputStream(fis.openStream());// 获得文件输入流
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
String lineTxt=null;
while((lineTxt=bufferedReader.readLine()) != null) {
System.out.println(lineTxt);
stringBuffer.append(lineTxt+",");
}
}
}
response.getWriter().println(stringBuffer.toString());// 终于成功了
}
} catch(Exception e) {
e.printStackTrace();
}
}
}