文件3. 文件复制

时间:2022-03-28 16:44:14

servlet层实现本地文件复制

.jsp界面

 1  <form action="<%=basePath %>fileAction" method="get" >
 2         <table>
 3             <tr>
 4                 <td>输入文件路径</td>
 5                 <td><input type="text" name="filePath" /></td>
 6             </tr>
 7             <tr>
 8                 <td>复制到:</td>
 9                 <td><input type="text" name="newPath"/></td>
10             </tr>
11        <tr>
12                 <td colspan="2"><input type="submit" value="复制"/></td>
13             </tr>
14             <tr>
15                 <td colspan="2"><input type="hidden" name="method" value="file"/></td>
16             </tr>
17         </table>
18  </form>

servlet层FileAction.java

 1 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
 2             throws ServletException, IOException {
 3         req.setCharacterEncoding("utf-8");
 4         resp.setCharacterEncoding("utf-8");
 5         resp.setContentType("text/html;charset=utf-8");
 6         PrintWriter out=resp.getWriter();
 7         String method=req.getParameter("method");
 8         
 9         if(method.equals("file")) {
10 //对文件进行操作
11             
12             
13     /*
14      * 判断文件是否存在
15      */
16 //          1. 获取请求中的文件路径(get方式,获得表单中的含有中文的值)
17 //           若是英文,则直接用req.getParameter("name");
18             String filePath=new String(req.getParameter("filePath").getBytes("iso8859-1"),"utf-8");
19 //                2. 根据路径定义相应的文件
20             File file=new File(filePath);
21 //                3. 使用exists();函数,判断生成的文件是否存在
22             boolean bool=file.exists();
23             if(bool==true) {
24             /*
25              * 文件存在,进行文件复制
26              */
27 //                1. 获取目标路径
28                 String newPath =new String(req.getParameter("newPath").getBytes("ISO8859-1"),"UTF-8");
29                 File newFilePa=new File(newPath);
            2. 判断目标路径是否存在,不存在则建立
30 if(!newFilePa.exists()) 31 newFilePa.mkdirs(); 32 FileInputStream fis = new FileInputStream(file); 33 File newFile=new File(newFilePa.getPath()+File.separator+file.getName()); 34 FileOutputStream fos=new FileOutputStream(newFile); //根据目标文件路径名创建文件输出流 35 int count; 36 byte buffer[]=new byte[1024]; 37 while((count=fis.read(buffer))!=-1) { 38 for(int i=0;i<count;i++) 39 fos.write(buffer[i]); 40 } 41 fos.close(); 42 fis.close(); 43 } else { 44 out.write("<script>alert('该文件不存在!');</script>"); 45 } 46 } 47 }

web.xml

1 <servlet>
2       <servlet-name>fileAction</servlet-name>
3       <servlet-class>servlet.FileAction</servlet-class>
4   </servlet>
5   <servlet-mapping>
6       <servlet-name>fileAction</servlet-name>
7       <url-pattern>/fileAction</url-pattern>
8   </servlet-mapping>