>>分享Java编程技术,对《Java面向对象编程》等书籍提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 26991 个阅读者 刷新本主题
 * 贴子主题:  利用org.apache.commons.io.FileUtils快速读写文件 回复文章 点赞(0)  收藏  
作者:flybird    发表时间:2019-08-14 15:13:40     消息  查看  搜索  好友  邮件  复制  引用

            

利用org.apache.commons.io.FileUtils快速读写文件

             利用org.apache.commons.io.FileUtils快速读写文件  

   String fileName = "C://11.txt";
  File file = new File(fileName);
  String fileContent = "";
  try {
   fileContent = org.apache.commons.io.FileUtils.readFileToString(file, "GBK");
  } catch (IOException e) {
   e.printStackTrace();
  }
  fileContent +="Helloworld";
  try {
   org.apache.commons.io.FileUtils.writeStringToFile(file, fileContent, "GBK");
  } catch (IOException e) {
   e.printStackTrace();
  }

                     其他参考

Commons IO方便读写文件的工具类:  http://laoyu.info/archives/282.html    

Commons IO是apache的一个开源的工具包,封装了IO操作的相关类,使用Commons IO可以很方便的读写文件,url源代码等.

普通地读取一个网页的源代码的代码可能如下

  1.    InputStream  in =   new   URL (   "http://laoyu.info"   ). openStream ( ) ;
  2.     try   {
  3.       InputStreamReader  inR =   new   InputStreamReader (  in   ) ;
  4.       BufferedReader  buf =   new   BufferedReader (  inR   ) ;
  5.       String  line ;
  6.       while   (   (  line = buf. readLine ( )   )   !=   null   )   {
  7.         System. out. println (  line   ) ;
  8.       }
  9.     }   finally   {
  10.      in. close ( ) ;
  11.     }

使用了Commons IO,则可以大大简化代码.如下:


  1.    InputStream  in =   new   URL (   "http://laoyu.info"   ). openStream ( ) ;
  2.     try   {
  3.       System. out. println (  IOUtils. toString (  in   )   ) ;
  4.     }   finally   {
  5.      IOUtils. closeQuietly (in ) ;
  6.     }

Commons IO里的常用类

FileUtils包含了文件操作的相关方法.
下面的代码用于读取磁盘上的某个文件:

  1.    File  file =   new   File ( "c:/test.txt" ) ;
  2.    List  lines = FileUtils. readLines (file,   "UTF-8" ) ;

FileSystemUtils 可以获得指定磁盘路径的可用空间

  1.    long  freeSpace = FileSystemUtils. freeSpace ( "d:/" ) ;

文件复制代码:

  1.    File  src =   new   File ( "src.txt" ) ;
  2.    File  dest =   new   File ( "dest.txt" ) ;
  3.   FileUtils. copyFile (src, dest ) ;

补充:
方便地下载文件到本地

  1.    InputStream  in =   new
  2.    URL ( "http://www.baidu.com/img/baidu_logo.gif" ). openStream ( ) ;
  3.       byte   [ ]  gif = IOUtils. toByteArray (in ) ;
  4.       //IOUtils.write(gif,new FileOutputStream(new File("c:/test.gif")));
  5.     FileUtils. writeByteArrayToFile ( new   File ( "c:/test.gif" ),gif ) ;
  6.     IOUtils. closeQuietly (in ) ;

      输入流复制到输出流  


  1.    public   class  IoTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception {  
  6.            // TODO Auto-generated method stub  
  7.           Writer write =  new  FileWriter( "c:\\kk.dat" );  
  8.           InputStream ins =  new  FileInputStream( new  File( "c:\\text.txt" ));  
  9.           IOUtils.copy(ins, write);  
  10.           write.close();  
  11.           ins.close();  
  12.       }  
  13.   }  

        文本写入指定文件  


  1.    public   class  FileWirterTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception{  
  6.            // TODO Auto-generated method stub  
  7.           String name =  "my name is panxiuyan" ;  
  8.           File file =   new  File( "c:\
    ame.txt" );  
  9.           FileUtils.writeStringToFile(file, name);  
  10.       }  
  11.   }  

            将输入流转换成文本  


  1.    public   class  URLIoTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception {  
  6.            // TODO Auto-generated method stub  
  7.           URL url =  new  URL( "http://www.dimurmill.com" );  
  8.           InputStream ins = url.openStream();  
  9.           String contents = IOUtils.toString(ins, "UTF-8" );  
  10.           System.out.println(  "Slashdot: "  + contents );  
  11.       }  
  12.   }  

        关闭相关流


  1.    public   class  IoCloseTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args) {  
  6.            // TODO Auto-generated method stub  
  7.           File file =  null ;  
  8.           InputStream ins =  null ;  
  9.            try {  
  10.               file =  new  File( "C:\\Test.java" );  
  11.               ins =  new  FileInputStream(file);  
  12.           } catch (Exception e){  
  13.               e.printStackTrace();  
  14.           } finally {  
  15.               IOUtils.closeQuietly(ins);  
  16.           }  
  17.       }  
  18.   }  

            文件复制


  1.    public   class  FileCopyTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception{  
  6.            // TODO Auto-generated method stub  
  7.           File srcfile =  new  File( "c:\\Test.java" );  
  8.           File destfile =  new  File( "c:\\Test.java.bak" );  
  9.           FileUtils.copyFile(srcfile, destfile);  
  10.       }  
  11.   }  

        文件复制指定的目录  


  1.    public   class  FileCopyTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception{  
  6.            // TODO Auto-generated method stub  
  7.           File srcfile =  new  File( "c:\\Test.java" );  
  8.           File destDir =  new  File( "D:\\" );  
  9.           FileUtils.copyFileToDirectory(srcfile, destDir);  
  10.       }  
  11.   }  

        网络流保存为文件  


  1.    public   class  URLToFileTest {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception{  
  6.            // TODO Auto-generated method stub  
  7.           URL url =  new  URL( "http://www.163.com" );  
  8.           File file =  new  File( "c:\\163.html" );  
  9.           FileUtils.copyURLToFile(url, file);  
  10.       }  
  11.   }  

            文件目录操作  


  1.    public   class  DirOper {  
  2.        /**
  3.         * @param args
  4.         */  
  5.        public   static   void  main(String[] args)  throws  Exception {  
  6.            // TODO Auto-generated method stub  
  7.           File dir =  new  File( "c:\\test" );  
  8.           FileUtils.cleanDirectory(dir); //清空目录下的文件  
  9.           FileUtils.deleteDirectory(dir); //删除目录和目录下的文件  
  10.       }  
  11.   }  

            目录大小  


  1.    long  size = FileUtils.sizeOfDirectory(dir);  

            目录操作  


  1.    File testFile =  new  File(  "testFile.txt"  );  
  2.         //如果不存在,新建  
  3.        // 如果存在,修改文件修改时间  
  4.       FileUtils.touch( testFile );  

            记录流的读取写入字节数  


  1.    File test =  new  File(  "test.dat"  );  
  2.    //输出流的统计  
  3.   CountingOutputStream countStream =  null ;  
  4.    //输入流的统计  
  5.    //CountingInputStream countStream = null;  
  6.    try  {  
  7.       FileOutputStream fos =  new  FileOutputStream( test );  
  8.       countStream =  new  CountingOutputStream( fos );  
  9.       countStream.write(  "Hello" .getBytes( ) );  
  10.   }  catch ( IOException ioe ) {  
  11.       System.out.println(  "Error writing bytes to file."  );  
  12.   }  finally  {  
  13.       IOUtils.closeQuietly( countStream );  
  14.   }  
  15.    if ( countStream !=  null  ) {  
  16.        int  bytesWritten = countStream.getCount( );  
  17.       System.out.println(  "Wrote "  + bytesWritten +  " bytes to test.dat"  );  
  18.   }  

            相同的内容写入不同的文本  


  1.    File test1 =  new  File( "split1.txt" );  
  2.   File test2 =  new  File( "split2.txt" );  
  3.   OutputStream outStream =  null ;  
  4.    try  {  
  5.       FileOutputStream fos1 =  new  FileOutputStream( test1 );  
  6.       FileOutputStream fos2 =  new  FileOutputStream( test2 );  
  7.        //包含不同的文本  
  8.       outStream =  new  TeeOutputStream( fos1, fos2 );  
  9.       outStream.write(  "One Two Three, Test" .getBytes( ) );  
  10.       outStream.flush( );  
  11.   }  catch ( IOException ioe ) {  
  12.       System.out.println(  "Error writing to split output stream"  );  
  13.   }  finally  {  
  14.       IOUtils.closeQuietly( outStream );  
  15.   }  

                                                ----------------------------
原文链接:https://blog.csdn.net/weixin_30765319/article/details/99967288

程序猿的技术大观园:www.javathinker.net



[这个贴子最后由 flybird 在 2020-01-09 22:45:35 重新编辑]

  Java面向对象编程-->变量的作用域和初始化
  JavaWeb开发-->使用过滤器
  JSP与Hibernate开发-->Java对象持久化技术概述
  Java网络编程-->对象的序列化与反序列化
  精通Spring-->
  Vue3开发-->计算属性和数据监听
  利用堆栈将中缀表达式转换成后缀表达式
  JDK17的新特性
  快速理解 函数式编程,响应式编程,链式编程
  JAVA锁相关知识总结
  Java关键字final、static使用总结
  BST 二叉搜索树
  面试官刁难:Java字符串可以引用传递吗?
  64匹马,8个赛道,找出跑得最快的4匹马
  最实用的10个重构小技巧排行榜,你都用过哪些?
  Eclipse的安装配置
  Java关键字final、static使用总结
  java中的Static、final、Static final各种用法
  Java入门实用代码:获取远程文件大小
  Java入门实用代码:数组元素的反转
  Java性能优化总结
  更多...
 IPIP: 已设置保密
楼主      
1页 0条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。