java对各种文件的操作详解

[size=medium]
Java代码   收藏代码
  1. java中提供了io类库,可以轻松的用java实现对文件的各种操作。下面就来说一下如何用java来实现这些操作。  
  2.    
  3. 新建目录<%@ page contentType="text/html;charset=gb2312"%>  
  4. <%  
  5. //String URL = request.getRequestURI();  
  6. String filePath="C:\\测试\\";  
  7. filePath=filePath.toString();//中文转换  
  8. java.io.File myFilePath=new java.io.File(filePath);  
  9. if(!myFilePath.exists())  
  10. myFilePath.mkdir();  
  11. %>  
  12.    
  13. 新建文件  
  14. <%@ page contentType="text/html;charset=gb2312"%>  
  15. <%@ page import="java.io.*" %>  
  16. <%  
  17. String filePath="c:/测试/newFile.txt";  
  18. filePath=filePath.toString();  
  19. File myFilePath=new File(filePath);  
  20. if(!myFilePath.exists())  
  21. myFilePath.createNewFile();  
  22. FileWriter resultFile=new FileWriter(myFilePath);  
  23. PrintWriter myFile=new PrintWriter(resultFile);  
  24. String content ="这是测试数据";  
  25. String strContent = content.toString();  
  26. myFile.println(strContent);  
  27. resultFile.close();  
  28. %>  
  29.    
  30. 删除文件<%@ page contentType="text/html;charset=gb2312"%>  
  31. <%  
  32. String filePath="c://测试//newFile.txt";  
  33. filePath=filePath.toString();  
  34. java.io.File myDelFile=new java.io.File(filePath);  
  35. if(myDelFile.exists())  
  36. {    
  37.     myDelFile.delete();  
  38.     out.println(filePath+"删除成功!!!");  
  39. }  
  40. else  
  41. {  
  42.     out.println(filePath+"该文件不存在");  
  43. }  
  44. %>  
  45. 文件拷贝<%@ page contentType="text/html; charset=gb2312" %>  
  46. <%@ page import="java.io.*" %>  
  47. <%  
  48. int bytesum=0;  
  49. int byteread=0;  
  50. //file:读到流中  
  51. InputStream inStream=new FileInputStream("c://测试//newFile.txt");  
  52. FileOutputStream fs=new FileOutputStream( "c://测试//copyFile.txt");  
  53. byte[]  buffer =new  byte[1444];  
  54. int length;  
  55. while ((byteread=inStream.read(buffer))!=-1)  
  56.  {  
  57.    out.println("<DT><B>"+byteread+"</B></DT>");  
  58.    bytesum+=byteread;  
  59.    out.println(bytesum);  
  60.    fs.write(buffer,0,byteread);  
  61.  }  
  62. inStream.close();  
  63. %>  
  64.    
  65. 整个文件夹拷贝  
  66. <%@ page contentType="text/html;charset=gb2312"%>  
  67. <%@ page import="java.io.*" %>  
  68. <%String url1="C:/aaa";  
  69.   String url2="d:/java/";  
  70.   (new File(url2)).mkdirs();  
  71.  File[] file=(new File(url1)).listFiles();  
  72.  for(int i=0;i  
  73.    
  74. 文件下载  
  75. <%@ page contentType="text/html; charset=gb2312"%>  
  76. <%@ page import="java.io.*" %>  
  77. <%  
  78.   String fileName = "newFile.txt".toString();  
  79.   //读到流中  
  80.   InputStream inStream=new FileInputStream("c://测试//newFile.txt");  
  81.   //设置输出的格式  
  82.   response.reset();  
  83.   response.setContentType("text/plain");  
  84.   response.addHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");  
  85.   //循环取出流中的数据  
  86.   byte[] b = new byte[100];  
  87.   int len;  
  88.   ServletOutputStream outStream = response.getOutputStream();  
  89.    
  90.   while((len=inStream.read(b)) >0)  
  91.   outStream.write(b,0,len);  
  92.   outStream.flush();  
  93.   outStream.close();  
  94.   inStream.close();  
  95. %>  
  96.    
  97. 数据库字段中的文件下载  
  98. <%@ page contentType="text/html;charset=gb2312"%>  
  99. <%@ page import="java.util.*,java.sql.*,java.io.*"%>  
  100. <%  
  101.     String id = request.getParameter("id");  
  102.     if(id==null)  
  103.     {   throw new Exception ("没有找到图片");  
  104.     }  
  105.     else  
  106.     {  
  107.        try  
  108.        {  
  109. com.gzrealmap.lib.jdbc.JDBCUtil  SqlBean= com.gzrealmap.lib.jdbc.JDBCUtil.getInstance();  
  110.                SqlBean.connect();  
  111.                String sql = "select * from innernews where id = '"+79+"'";  
  112.                ResultSet rs = SqlBean.queryforUpdate(sql);  
  113.                rs.next();  
  114.                //String fileNamedb = rs.getString("imageName");  
  115.                String file= rs.getString("acc");  
  116.                //String fileName = new String(fileNamedb.getBytes(),"iso-8859-1");  
  117.                String fileName = "a.jpg";  
  118.                 response.setHeader("Content-Disposition",  "inline; filename=\"" + fileName + "\"");      
  119.                String filter = fileName.substring(fileName.lastIndexOf("."));  
  120.                 
  121.                if(filter.equals(".txt"))  
  122.                {  
  123.                    response.setContentType("text/plain");  
  124.                }  
  125.                else if(filter.equals(".doc")||filter.equals(".dot"))  
  126.                {  
  127.                    response.setContentType("application/msword");  
  128.                }  
  129.                else  
  130.                {  
  131.                  response.setContentType("image/jpeg;charset=GB2312");  
  132.                }  
  133.                ServletOutputStream o = response.getOutputStream();  
  134.                //o.write(file);  
  135.                out.println(file);  
  136.                //o.flush();  
  137.                //o.close();  
  138.                SqlBean.disconnect();  
  139.        }  
  140.         catch(Exception ex)  
  141.        {  
  142.            out.println(ex.getMessage());  
  143.        }  
  144.     }    
  145. %>  
  146.    
  147. 把网页保存成文件<%@ page contentType="text/html;charset=gb2312"%>  
  148. <%@ page import="java.text.*,java.util.*,java.net.*,java.io.*"%>  
  149. <%  
  150.  URL stdURL = null;  
  151.  BufferedReader stdIn = null;  
  152.  PrintWriter stdOut = null;  
  153.  try {  
  154.   stdURL = new URL("http://www.163.com");  
  155.  }  
  156.  catch (MalformedURLException e) {  
  157.    throw e;  
  158.  }  
  159.    
  160. try {  
  161.     //将字节流转变成为字符流  
  162.     stdIn = new BufferedReader(new InputStreamReader(stdURL.openStream()));  
  163.     String theFileName = "c://测试//163.html";  
  164.     stdOut = new PrintWriter(new BufferedWriter(new FileWriter(theFileName.toString())));  
  165.  }  
  166.  catch (IOException e) {  
  167.  }  
  168.    
  169.  /***把URL指定的页面以流的形式读出,写成指定的文件***/  
  170.  try {  
  171.     String strHtml = "";  
  172.    while((strHtml = stdIn.readLine())!=null) {  
  173.    stdOut.println(strHtml);  
  174.    }  
  175.  }  
  176.  catch (IOException e) {  
  177.    throw e;  
  178.  }  
  179.  finally {    
  180.    try {  
  181.      if(stdIn != null)  
  182.        stdIn.close();  
  183.      if(stdOut != null)  
  184.        stdOut.close();  
  185.        }  
  186.    catch (Exception e) {  
  187.      System.out.println(e);  
  188.    }  
  189.  }  
  190. %>  
  191.    
  192. 直接下载网上的文件  
  193. <%@ page contentType="text/html;charset=gb2312"%>  
  194. <%@ page import="java.io.*"%>  
  195. <%@ page import="java.net.*"%>  
  196. <%  
  197.   int bytesum=0;  
  198.   int byteread=0;  
  199.   URL url = new URL("http://pimg.163.com/sms/micheal/logo.gif");  
  200.   URLConnection conn = url.openConnection();  
  201.   InputStream inStream = conn.getInputStream();  
  202.    
  203.   /** 
  204.   String theFileName = "c:/测试/logo.gif"; 
  205.   theFileName = theFileName.toString(); 
  206.   File myFilePath=new File(theFileName); 
  207.   if(!myFilePath.exists()) 
  208.   myFilePath.createNewFile(); 
  209.   **/  
  210.    
  211.   FileOutputStream fs=new FileOutputStream("c:/测试/logo2.gif");  
  212.   byte[]  buffer =new  byte[1444];  
  213.     while ((byteread=inStream.read(buffer))!=-1)  
  214.     {  
  215.        out.println("<DT><B>"+byteread+"</B></DT>");  
  216.        bytesum+=byteread;  
  217.        //System.out.println(bytesum);  
  218.        fs.write(buffer,0,byteread);  
  219.      }  
  220. %>  
  221.    
  222. 按行读文件 <%@ page contentType="text/html; charset=gb2312" %>  
  223. <%@ page import="java.io.*" %>  
  224. <%  
  225. FileReader myFileReader=new FileReader("c:/哈哈.txt");  
  226. BufferedReader myBufferedReader=new BufferedReader(myFileReader);  
  227. String myString=null;  
  228. String resultString=new String();  
  229. while((myString=myBufferedReader.readLine())!=null) {  
  230. resultString=resultString+myString+"<br>";  
  231. }  
  232. out.println(resultString);  
  233. myFileReader.close();  
  234. %>  
  235.    
  236. 对word文档的处理(上传与下载)<%@ page contentType="application/msword" %>  
  237.   
  238. <%  
  239.    response.setHeader("Content-disposition","inline; filename=test1.doc"); //线上浏览方式  
  240.   // response.setHeader("Content-disposition","attachment; filename=test1.doc");//下载方式  
  241.    //以上这行设定传送到前端浏览器时的档名为test1.doc  
  242.    //就是靠这一行,让前端浏览器以为接收到一个word档  
  243. %>  
  244. //然后输出动态内容就可以得到一个word文档了  
  245.    
  246. 1,打开:  
  247. 1)文件头上加:<%@ page  contentType="application/msword"%>   
  248. xml文件里:  
  249.   
  250.         doc  
  251.         application/msword  
  252.   
  253. 2)可以用js,以下代码来自引用:  
  254. <%@ page contentType="text/html;charset=gb2312" import"java.io.*"%>  
  255.   
  256.   
  257. var wrd=new ActiveXObject("Word.Application")  
  258. wrd.visible=true  
  259. alert ("您的"+wrd.Application.Caption+"安装路径为:\n"+wrd.Application.Path+"\n版本号是:"+ wrd.Application.version+"\n注册使用者是:"+wrd.Application.UserName)  
  260. wrd.Documents.Add()  
  261. //wrd.Documents.Open("c:\\exam.doc")  
  262. wrd.Selection.TypeText("This is some text.")  
  263. wrd.Application.Activate()  
  264. wrd.ActiveDocument.SaveAs("c:\\exam111.doc")  
  265. wrd=null  
  266.   
  267.   
  268.    
  269. 2,下载:  
  270. <%@ page contentType="text/html;charset=gb2312" import"java.io.*"%>  
  271. <%// 得到文件名字和路径  
  272.   String filename = "jsp.doc";  
  273.   String filepath = "C:\\";  
  274.    
  275.   // 设置响应头和下载保存的文件名  
  276.   response.setContentType("APPLICATION/OCTET-STREAM");  
  277.   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");  
  278.    
  279.   // 打开指定文件的流信息  
  280.   java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);  
  281.   //FileOutputStream out  = new FileOutputStream(filepath+"测试\\" + filename);  
  282.   // 写出流信息  
  283.   int i;  
  284.   while ((i=fileInputStream.read()) != -1) {  
  285.    out.write(i);  
  286.   }  
  287.   fileInputStream.close();  
  288.   out.close();  
  289.  %>   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值