public class servlet extends HttpServlet{
private ServletConfig servletConfig;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//bianli(req, resp);
// TODO Auto-generated method stub
//resp.getOutputStream().write("你好".getBytes());
//String usernameString=req.getParameter("username");
//resp.getOutputStream().write(usernameString.getBytes());
bianli(req, resp);
//super.doGet(req, resp);
//int a=0;
//a++;
//String method=req.getMethod();
//String aString=servletConfig.getInitParameter("data");
//resp.getOutputStream().write(Integer.toString(a).getBytes());
//resp.getOutputStream().write(aString.getBytes());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
//super.init();
this.servletConfig=config;
}
public void bianli(HttpServletRequest req, HttpServletResponse resp){
//File file=new File("D:"+File.separator+"test");
File file=new File("D:");
File[]files=file.listFiles();
/*
try {
resp.getOutputStream().write(files[1].getName().getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
boolean youmeiyou=false;
String usernameString=req.getParameter("username");
for (int i = 0; i < files.length; i++) {
if (files[i].getName().contains(usernameString)) {
youmeiyou=true;
InputStream in=null;
OutputStream outputStream=null;
int len=0;
byte[]b=new byte[1024];
resp.setHeader("content-disposition", "attachment;filename="+files[i].getName());
try {
outputStream=resp.getOutputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in=new FileInputStream(files[i]);
while ((len=in.read(b))>0) {
outputStream.write(b,0,len);
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}return;
}
/*if(!files[i].getName().contains(usernameString)){
try {
resp.getOutputStream().write("你搜索的文件不存在".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
}
if (youmeiyou==false) {
try {
resp.getOutputStream().write("你搜索的文件不存在".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}