java中提供了io类库,可以轻松的用java实现对文件的各种操作。下面就来说一下如何用java来实现这些操作。
 
新建目录

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%
  3. //String URL = request.getRequestURI();
  4. String filePath="C:\\测试\\";
  5. filePath=filePath.toString();//中文转换
  6. java.io.File myFilePath=new java.io.File(filePath);
  7. if(!myFilePath.exists())
  8. myFilePath.mkdir();
  9. %>

新建文件

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%@ page import="java.io.*" %>
  3. <%
  4. String filePath="c:/测试/newFile.txt";
  5. filePath=filePath.toString();
  6. File myFilePath=new File(filePath);
  7. if(!myFilePath.exists())
  8. myFilePath.createNewFile();
  9. FileWriter resultFile=new FileWriter(myFilePath);
  10. PrintWriter myFile=new PrintWriter(resultFile);
  11. String content ="这是测试数据";
  12. String strContent = content.toString();
  13. myFile.println(strContent);
  14. resultFile.close();
  15. %>


删除文件

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%
  3. String filePath="c://测试//newFile.txt";
  4. filePath=filePath.toString();
  5. java.io.File myDelFile=new java.io.File(filePath);
  6. if(myDelFile.exists())
  7. {  
  8.     myDelFile.delete();
  9.     out.println(filePath+"删除成功!!!");
  10. }
  11. else
  12. {
  13.     out.println(filePath+"该文件不存在");
  14. }
  15. %>

文件拷贝

  1. <%@ page contentType="text/html; charset=gb2312" %>
  2. <%@ page import="java.io.*" %>
  3. <%
  4. int bytesum=0;
  5. int byteread=0;
  6. //file:读到流中
  7. InputStream inStream=new FileInputStream("c://测试//newFile.txt");
  8. FileOutputStream fs=new FileOutputStream( "c://测试//copyFile.txt");
  9. byte[]  buffer =new  byte[1444];
  10. int length;
  11. while ((byteread=inStream.read(buffer))!=-1)
  12.  {
  13.    out.println("<DT><B>"+byteread+"</B></DT>");
  14.    bytesum+=byteread;
  15.    out.println(bytesum);
  16.    fs.write(buffer,0,byteread);
  17.  }
  18. inStream.close();
  19. %>

整个文件夹拷贝

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%@ page import="java.io.*" %>
  3. <%String url1="C:/aaa";
  4.   String url2="d:/java/";
  5.   (new File(url2)).mkdirs();
  6.  File[] file=(new File(url1)).listFiles();
  7.  for(int i=0;i<file.length;i++){
  8.   if(file[i].isFile()){
  9.    file[i].toString();
  10.    FileInputStream input=new FileInputStream(file[i]);
  11.    FileOutputStream output=new FileOutputStream(url2+"/"+(file[i].getName()).toString());
  12.    byte[] b=new byte[1024*5];
  13.     int len;
  14.     while((len=input.read(b))!=-1){
  15.     output.write(b,0,len);
  16.     }
  17.     output.flush();
  18.     output.close();
  19.     input.close();
  20.   }
  21.  }
  22. %>

文件下载

  1. <%@ page contentType="text/html; charset=gb2312"%>
  2. <%@ page import="java.io.*" %>
  3. <%
  4.   String fileName = "newFile.txt".toString();
  5.   //读到流中
  6.   InputStream inStream=new FileInputStream("c://测试//newFile.txt");
  7.   //设置输出的格式
  8.   response.reset();
  9.   response.setContentType("text/plain");
  10.   response.addHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
  11.   //循环取出流中的数据
  12.   byte[] b = new byte[100];
  13.   int len;
  14.   ServletOutputStream outStream = response.getOutputStream();
  15.   while((len=inStream.read(b)) >0)
  16.   outStream.write(b,0,len);
  17.   outStream.flush();
  18.   outStream.close();
  19.   inStream.close();
  20. %>

数据库字段中的文件下载

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%@ page import="java.util.*,java.sql.*,java.io.*"%>
  3. <%
  4.     String id = request.getParameter("id");
  5.     if(id==null)
  6.     {   throw new Exception ("没有找到图片");
  7.     }
  8.     else
  9.     {
  10.        try
  11.        {
  12. com.gzrealmap.lib.jdbc.JDBCUtil  SqlBean= com.gzrealmap.lib.jdbc.JDBCUtil.getInstance();
  13.                SqlBean.connect();
  14.                String sql = "select * from innernews where id = '"+79+"'";
  15.                ResultSet rs = SqlBean.queryforUpdate(sql);
  16.                rs.next();
  17.                //String fileNamedb = rs.getString("imageName");
  18.                String file= rs.getString("acc");
  19.                //String fileName = new String(fileNamedb.getBytes(),"iso-8859-1");
  20.                String fileName = "a.jpg";
  21.                 response.setHeader("Content-Disposition",  "inline; filename=\"" + fileName + "\"");    
  22.                String filter = fileName.substring(fileName.lastIndexOf("."));
  23.               
  24.                if(filter.equals(".txt"))
  25.                {
  26.                    response.setContentType("text/plain");
  27.                }
  28.                else if(filter.equals(".doc")||filter.equals(".dot"))
  29.                {
  30.                    response.setContentType("application/msword");
  31.                }
  32.                else
  33.                {
  34.                  response.setContentType("image/jpeg;charset=GB2312");
  35.                }
  36.                ServletOutputStream o = response.getOutputStream();
  37.                //o.write(file);
  38.                out.println(file);
  39.                //o.flush();
  40.                //o.close();
  41.                SqlBean.disconnect();
  42.        }
  43.         catch(Exception ex)
  44.        {
  45.            out.println(ex.getMessage());
  46.        }
  47.     }  
  48. %>

把网页保存成文件

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%@ page import="java.text.*,java.util.*,java.net.*,java.io.*"%>
  3. <%
  4.  URL stdURL = null;
  5.  BufferedReader stdIn = null;
  6.  PrintWriter stdOut = null;
  7.  try {
  8.   stdURL = new URL("<a href="http://www.163.com/">http://www.163.com</a>");
  9.  }
  10.  catch (MalformedURLException e) {
  11.    throw e;
  12.  }
  13. try {
  14.     //将字节流转变成为字符流
  15.     stdIn = new BufferedReader(new InputStreamReader(stdURL.openStream()));
  16.     String theFileName = "c://测试//163.html";
  17.     stdOut = new PrintWriter(new BufferedWriter(new FileWriter(theFileName.toString())));
  18.  }
  19.  catch (IOException e) {
  20.  }
  21.  /***把URL指定的页面以流的形式读出,写成指定的文件***/
  22.  try {
  23.     String strHtml = "";
  24.    while((strHtml = stdIn.readLine())!=null) {
  25.    stdOut.println(strHtml);
  26.    }
  27.  }
  28.  catch (IOException e) {
  29.    throw e;
  30.  }
  31.  finally {  
  32.    try {
  33.      if(stdIn != null)
  34.        stdIn.close();
  35.      if(stdOut != null)
  36.        stdOut.close();
  37.        }
  38.    catch (Exception e) {
  39.      System.out.println(e);
  40.    }
  41.  }
  42. %>

直接下载网上的文件

  1. <%@ page contentType="text/html;charset=gb2312"%>
  2. <%@ page import="java.io.*"%>
  3. <%@ page import="java.net.*"%>
  4. <%
  5.   int bytesum=0;
  6.   int byteread=0;
  7.   URL url = new URL("<a href="http://pimg.163.com/sms/micheal/logo.gif">http://pimg.163.com/sms/micheal/logo.gif</a>");
  8.   URLConnection conn = url.openConnection();
  9.   InputStream inStream = conn.getInputStream();
  10.   /**
  11.   String theFileName = "c:/测试/logo.gif";
  12.   theFileName = theFileName.toString();
  13.   File myFilePath=new File(theFileName);
  14.   if(!myFilePath.exists())
  15.   myFilePath.createNewFile();
  16.   **/
  17.   FileOutputStream fs=new FileOutputStream("c:/测试/logo2.gif");
  18.   byte[]  buffer =new  byte[1444];
  19.     while ((byteread=inStream.read(buffer))!=-1)
  20.     {
  21.        out.println("<DT><B>"+byteread+"</B></DT>");
  22.        bytesum+=byteread;
  23.        //System.out.println(bytesum);
  24.        fs.write(buffer,0,byteread);
  25.      }
  26. %>

按行读文件

  1. <%@ page contentType="text/html; charset=gb2312" %>
  2. <%@ page import="java.io.*" %>
  3. <%
  4. FileReader myFileReader=new FileReader("c:/哈哈.txt");
  5. BufferedReader myBufferedReader=new BufferedReader(myFileReader);
  6. String myString=null;
  7. String resultString=new String();
  8. while((myString=myBufferedReader.readLine())!=null) {
  9. resultString=resultString+myString+"
  10. ";
  11. }
  12. out.println(resultString);
  13. myFileReader.close();
  14. %>

对word文档的处理(上传与下载)

  1. <%@ page contentType="application/msword" %>
  2. <!-- 以上这行设定本网页为excel格式的网页 -->
  3. <%
  4.    response.setHeader("Content-disposition","inline; filename=test1.doc"); //线上浏览方式
  5.   // response.setHeader("Content-disposition","attachment; filename=test1.doc");//下载方式
  6.    //以上这行设定传送到前端浏览器时的档名为test1.doc
  7.    //就是靠这一行,让前端浏览器以为接收到一个word档
  8. %>
  9. //然后输出动态内容就可以得到一个word文档了

1,打开:
1)文件头上加:

  1. <%@ page  contentType="application/msword"%> 
  2. xml文件里:
  3. <mime-mapping>
  4.         <extension>doc</extension>
  5.         <mime-type>application/msword</mime-type>
  6. </mime-mapping>

2)可以用js,以下代码来自引用:

]]>




 
2,下载:

  1. <%@ page contentType="text/html;charset=gb2312" import= "java.io.*"%>
  2. <%// 得到文件名字和路径
  3.   String filename = "jsp.doc";
  4.   String filepath = "C:\\";
  5.   // 设置响应头和下载保存的文件名
  6.   response.setContentType("APPLICATION/OCTET-STREAM");
  7.   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
  8.   // 打开指定文件的流信息
  9.   java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);
  10.   //FileOutputStream out  = new FileOutputStream(filepath+"测试\\" + filename);
  11.   // 写出流信息
  12.   int i;
  13.   while ((i=fileInputStream.read()) != -1) {
  14.    out.write(i);
  15.   }
  16.   fileInputStream.close();
  17.   out.close()
  18.  %>