文件操作
文件操作
目的:
1、继续掌握JavaBean的概念。
2、掌握JSP的输入和输出流。
3、掌握在页面中读写文件中的数据。
4、掌握如何进行文件操作。
网页上的文件操作管理,可以实现文件上传功能和下载功能,显示文件列表和读取文件内容功能。
(1)实现文件上传功能。

(2)实现列出服务目录所有文件和子目录的功能,并且能够显示指定文件内容功能。

(3)实现文件下载功能。

部分代码如下:
public String getReadContent() {
try {
File file = new File(fileDir, fileName);
FileReader in = new FileReader(file);
BufferedReader inTwo = new BufferedReader(in);
StringBuffer stringbuffer = new StringBuffer();
String s = null;
while ((s = inTwo.readLine()) != null) {
stringbuffer.append("\n" + s);
}
String temp = new String(stringbuffer);
readContent = "<TextArea rows=10 cols=62>" + temp + "</TextArea>";
} catch (IOException e) {
readContent = "<TextArea rows=8 cols=62>" + "请选择一个文件"
+ "</TextArea>";
}
return readContent;
}
文件下载的处理
<% response.reset();
try{
String str=request.getParameter("name1"); //获得响应客户的输出流:
str=new String(str.getBytes("iso8859-1"),"gb2312");
String path = request.getRealPath("/");
path = path.substring(0,path.lastIndexOf("\\"));
path = path + "\\";
File fileLoad=new File(path,str);//下载文件位置:
response.reset();
OutputStream o=response.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(o);
byte b[]=new byte[500]; //输出文件用的字节数组,每次发送500个字节到输出流:
response.setHeader("Content-disposition","attachment;filename="+new String(str.getBytes("gb2312"),"iso8859-1")); //客户使用保存文件的对话框
response.setContentType("application/x-tar");//通知客户文件的MIME类型:
long fileLength=fileLoad.length();//通知客户文件的长度:
String length=String.valueOf(fileLength);
response.setHeader("Content_Length",length);
FileInputStream in=new FileInputStream(fileLoad);//读取文件,并发送给客户下载:
int n=0;
while((n=in.read(b))!=-1)
{ bos.write(b,0,n);
}
bos.close();
}catch(Exception e){System.out.print(e);}
response.reset();
%>
文件上传的处理
<%
int MAX_SIZE = 102400 * 102400; //定义上载文件的最大字节
String rootPath; // 创建根路径的保存变量
DataInputStream in = null; //声明文件读入类
FileOutputStream fileOut = null;
String remoteAddr = request.getRemoteAddr(); //取得客户端的网络地址
String serverName = request.getServerName(); //获得服务器的名字
String realPath = request.getRealPath("/");//取得互联网程序的绝对地址
realPath = realPath.substring(0, realPath.lastIndexOf("\\"));
rootPath = realPath + "\\"; //创建文件的保存目录
out.println("上传文件保存目录为" + rootPath);
String contentType = request.getContentType(); //取得客户端上传的数据类型
try {
if (contentType.indexOf("multipart/form-data") >= 0) {
in = new DataInputStream(request.getInputStream()); //读入上传的数据
int formDataLength = request.getContentLength();//取得客户端上传的数据的长度
if (formDataLength > MAX_SIZE) {
out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
return;
}
byte dataBytes[] = new byte[formDataLength]; //保存上传文件的数据
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) { //上传的数据保存在byte数组
byteRead = in.read(dataBytes, totalBytesRead,
formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes); //根据byte数组创建字符串
String saveFile = file.substring(file.indexOf("filename=\"") + 10); //取得上传的数据的文件名
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(
saveFile.lastIndexOf("\\") + 1,
saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,
contentType.length());//取得数据的分隔字符串
String fileName = rootPath + saveFile;
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;//取得文件数据的开始的位置
int endPos = ((file.substring(0, boundaryLocation))
.getBytes()).length; //取得文件数据的结束的位置
File checkFile = new File(fileName); //检查上载文件是否存在
if (checkFile.exists()) {
out.println("<p>" + saveFile + "文件已经存在.</p>");
}
File fileDir = new File(rootPath);//检查上载文件的目录是否存在
if (!fileDir.exists()) {
fileDir.mkdirs();
}
fileOut = new FileOutputStream(fileName); //创建文件的写出类
fileOut.write(dataBytes, startPos, (endPos - startPos)); //保存文件的数据
fileOut.close();
out.println("<P><font color=red size=5>" + saveFile
+ "文件成功上传.</font></p>");
} else {
String content = request.getContentType();
out.println("<p>上传的数据类型不是是multipart/form-data</p>");
}
} catch (Exception ex) {
throw new ServletException(ex.getMessage());
}
%>
详细的代码在附件(file.zip)中给出。