一、要求
使用MVC模式按行读取服务器上的文件。在一个JSP页面中输人文件的路径、名字,单击“读取”按钮,将信息提交给servlet,servlet将读取文件放入Javabean数据模型中,然后请求JSP页面显示Javabean中的数据。
二、参考代码
Web.xml
<servlet>
<servlet-name>readFileByLine</servlet-name>
<servlet-class>myservlet.control.Shiyan2_Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>readFileByLine</servlet-name>
<url-pattern>/readFileByLine</url-pattern>
</servlet-mapping>
Shiyan2_Bean.java
package mybean.data;
public class Shiyan2_Bean {
StringBuffer content;
public void setContent(StringBuffer str) {
content = str;
}
public StringBuffer getContent() {
return content;
}
}
readFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body bgcolor = cyan><font size= 2>
<jsp:useBean id= "fileBean" class ="mybean.data.Shiyan2_Bean" scope= "request"/>
<form action = "readFileByLine" method = "post" name = "form">
输入文件的路径(如:d:/2000):
<input type= "text" name= "filePath" size= 12>
<br>输人文件的名字(如:Hello.java):
<input type= "text" name= "fileName" size= 9>
<br><input type= "submit" value= "读取" name = "submit">
</form>
<b><br>读入的内容:<br>
<br><%= fileBean.getContent()%>
</b>
</font></body></HTML>
Shiyan2_Servlet.java
package myservlet.control;
import mybean.data.Shiyan2_Bean;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Shiyan2_Servlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException{
request.setCharacterEncoding("gb2312");
Shiyan2_Bean fileBean = new Shiyan2_Bean();
//创建Javabean对象
request.setAttribute("fileBean" , fileBean) ;
String filePath = request.getParameter("filePath");
String fileName = request.getParameter("fileName" );
boolean boo= filePath!= null&&filePath.length()> 0;
boo = fileName!= null&&fileName.length()> 0;
StringBuffer buffer = new StringBuffer();
if(boo) {
RandomAccessFile in= null;
try{ in = new RandomAccessFile(filePath+ "/" + fileName, "rw");
long length = in.length();
long position = 0;
in.seek(position) ;
while(position < length) {
String str = in.readLine();
byte b[] = str.getBytes("iso-8859-1");
str = new String(b);
position = in.getFilePointer();
buffer.append("<br>" + str);
}
fileBean.setContent(buffer);
}
catch(IOException exp){}
}
RequestDispatcher dispatcher =
request.getRequestDispatcher("readFile.jsp");
dispatcher.forward(request, response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException{
doPost(request, response);
}
}
三、结果展示
运行readFile.jsp并输入文件所在路径及文件名字:
点击提交后会读取磁盘E:\java web目录下的Car.java文件: