java中的文件操作

34 篇文章 0 订阅
12 篇文章 0 订阅

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

生成文件时,可用下边的方法来设置流的编码

PrintWriter myFile =new PrintWriter(new OutputStreamWriter(new FileOutputStream(文件名),"gb2312"));
 
新建目录

  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.  
  16.   while((len=inStream.read(b)) >0)
  17.   outStream.write(b,0,len);
  18.   outStream.flush();
  19.   outStream.close();
  20.   inStream.close();
  21. %>

数据库字段中的文件下载

  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. %>
  49.  

把网页保存成文件

  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.  
  14. try {
  15.     //将字节流转变成为字符流
  16.     stdIn = new BufferedReader(new InputStreamReader(stdURL.openStream()));
  17.     String theFileName = "c://测试//163.html";
  18.     stdOut = new PrintWriter(new BufferedWriter(new FileWriter(theFileName.toString())));
  19.  }
  20.  catch (IOException e) {
  21.  }
  22.  
  23.  /***把URL指定的页面以流的形式读出,写成指定的文件***/
  24.  try {
  25.     String strHtml = "";
  26.    while((strHtml = stdIn.readLine())!=null) {
  27.    stdOut.println(strHtml);
  28.    }
  29.  }
  30.  catch (IOException e) {
  31.    throw e;
  32.  }
  33.  finally {  
  34.    try {
  35.      if(stdIn != null)
  36.        stdIn.close();
  37.      if(stdOut != null)
  38.        stdOut.close();
  39.        }
  40.    catch (Exception e) {
  41.      System.out.println(e);
  42.    }
  43.  }
  44. %>

直接下载网上的文件

  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.   /**
  12.   String theFileName = "c:/测试/logo.gif";
  13.   theFileName = theFileName.toString();
  14.   File myFilePath=new File(theFileName);
  15.   if(!myFilePath.exists())
  16.   myFilePath.createNewFile();
  17.   **/
  18.  
  19.   FileOutputStream fs=new FileOutputStream("c:/测试/logo2.gif");
  20.   byte[]  buffer =new  byte[1444];
  21.     while ((byteread=inStream.read(buffer))!=-1)
  22.     {
  23.        out.println("<DT><B>"+byteread+"</B></DT>");
  24.        bytesum+=byteread;
  25.        //System.out.println(bytesum);
  26.        fs.write(buffer,0,byteread);
  27.      }
  28. %>

按行读文件

  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.  
  3. xml文件里:
  4. <mime-mapping>
  5.         <extension>doc</extension>
  6.         <mime-type>application/msword</mime-type>
  7. </mime-mapping>

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

<%@ page contentType="text/html;charset=gb2312" import= "java.io.*"%>




 
2,下载:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值