当前位置: 首页 > news >正文

Java那些事之磁盘操作

磁盘操作和文件操作有时密不可分,上一次和大家分享了文件操作的基本用法,这次顺带把磁盘的操作也一起介绍一下,也好方便大家配合使用。

磁盘操作主要包括新建目录,复制文件,剪切,删除,以及压缩等。下面一一附上代码,代码中注释还是很详细的,就不在此做过多解释了。

  1  /**
  2   *  @author  Chen.Lu
  3   * 磁盘文件或文件夹操作的通用方法
  4    */
  5  public   class  DiskHelper {
  6       /**
  7       * 新建目录
  8       *  @param  folderPath String 如 c:/fqf
  9       *  @return  boolean
 10        */
 11      public   void  newFolder(String folderPath) {
 12          try  {
 13             String filePath  =  folderPath;
 14             filePath  =  filePath.toString();
 15             java.io.File myFilePath  =   new  java.io.File(filePath);
 16              if  ( ! myFilePath.exists()) {
 17                 myFilePath.mkdir();
 18                 CheckMethods.PrintDebugMessage( " 新建目录操作成功: " + folderPath);
 19             }
 20         }
 21          catch  (Exception e) {
 22             CheckMethods.PrintInfoMessage( " 新建目录操作出错: " + folderPath);
 23             LogHelper.WriteLog(LogHelper.logger_Error, CommonValues.Log_Detail_Level,  " info " " 新建目录操作出错: " + folderPath);
 24             e.printStackTrace();
 25         }
 26     }
 27 
 28      /**
 29       * 新建文件
 30       *  @param  filePathAndName String 文件路径及名称 如c:/fqf.txt
 31       *  @param  fileContent String 文件内容
 32       *  @return  boolean
 33        */
 34      public   void  newFile(String filePathAndName, String fileContent) {
 35 
 36          try  {
 37             String filePath  =  filePathAndName;
 38             filePath  =  filePath.toString();
 39             File myFilePath  =   new  File(filePath);
 40              if  ( ! myFilePath.exists()) {
 41                 myFilePath.createNewFile();
 42                 CheckMethods.PrintDebugMessage( " 新建文件操作成功: " + filePathAndName);
 43             }
 44             FileWriter resultFile  =   new  FileWriter(myFilePath);
 45             PrintWriter myFile  =   new  PrintWriter(resultFile);
 46             String strContent  =  fileContent;
 47             myFile.println(strContent);
 48             resultFile.close();
 49         }
 50          catch  (Exception e) {
 51             CheckMethods.PrintInfoMessage( " 新建文件操作出错: " + filePathAndName);
 52             LogHelper.WriteLog(LogHelper.logger_Error, CommonValues.Log_Detail_Level,  " info " " 新建文件操作出错: " + filePathAndName);
 53             e.printStackTrace();
 54 
 55         }
 56 
 57     }
 58 
 59      /**
 60       * 删除文件
 61       *  @param  filePathAndName String 文件路径及名称 如c:/fqf.txt
 62       *  @param  fileContent String
 63       *  @return  boolean
 64        */
 65      public   void  delFile(String filePathAndName) {
 66          try  {
 67             String filePath  =  filePathAndName;
 68             filePath  =  filePath.toString();
 69             java.io.File myDelFile  =   new  java.io.File(filePath);
 70             myDelFile.delete();
 71             CheckMethods.PrintDebugMessage( " 删除文件操作成功: " + filePathAndName);
 72         }
 73          catch  (Exception e) {
 74             CheckMethods.PrintInfoMessage( " 删除文件操作出错: " + filePathAndName);
 75             LogHelper.WriteLog(LogHelper.logger_Error, CommonValues.Log_Detail_Level,  " info " " 删除文件操作出错: " + filePathAndName);
 76             e.printStackTrace();
 77 
 78         }
 79 
 80     }
 81 
 82      /**
 83       * 删除文件夹
 84   
 85 
 86       *  @param  filePathAndName String 文件夹路径及名称 如c:/fqf
 87       *  @param  fileContent String
 88       *  @return  boolean
 89        */
 90      public   void  delFolder(String folderPath) {
 91          try  {
 92             delAllFile(folderPath);  // 删除完里面所有内容
 93             String filePath  =  folderPath;
 94             filePath  =  filePath.toString();
 95             java.io.File myFilePath  =   new  java.io.File(filePath);
 96             myFilePath.delete();  // 删除空文件夹
 97             CheckMethods.PrintDebugMessage( " 删除文件夹操作成功: " + folderPath);
 98         }
 99          catch  (Exception e) {
100             CheckMethods.PrintInfoMessage( " 删除文件夹操作出错: " + folderPath);
101             LogHelper.WriteLog(LogHelper.logger_Error, CommonValues.Log_Detail_Level,  " info " " 删除文件夹操作出错: " + folderPath);
102             e.printStackTrace();
103 
104         }
105     }
106      /**
107       * 删除文件夹里面的所有文件
108       *  @param  path String 文件夹路径 如 c:/fqf
109        */
110      public   void  delAllFile(String path) {
111         CheckMethods.PrintDebugMessage(path );
112         File file  =   new  File(path);
113          if  ( ! file.exists()) {
114              return ;
115         }
116          if  ( ! file.isDirectory()) {
117              return ;
118         }
119         String[] tempList  =  file.list();
120         File temp  =   null ;
121          for  ( int  i  =   0 ; i  <  tempList.length; i ++ ) {
122              if  (path.endsWith(File.separator)) {
123                 temp  =   new  File(path  +  tempList[i]);
124             }
125              else  {
126                 temp  =   new  File(path  +  File.separator  +  tempList[i]);
127             }
128              if  (temp.isFile()) {
129                temp.delete();
130             }
131              if  (temp.isDirectory()) {
132                 delAllFile(path + " / " +  tempList[i]); // 先删除文件夹里面的文件
133                 delFolder(path + " / " +  tempList[i]); // 再删除空文件夹
134             }
135         }
136     }
137 
138      /**
139       * 复制单个文件
140       *  @param  oldPath String 原文件路径 如:c:/fqf.txt
141       *  @param  newPath String 复制后路径 如:f:/fqf.txt
142       *  @return  boolean
143        */
144      public   void  copyFile(String oldPath, String newPath) {
145          try  {
146              int  bytesum  =   0 ;
147              int  byteread  =   0 ;
148             File oldfile  =   new  File(oldPath);
149              if  (oldfile.exists()) {  // 文件存在时
150                 InputStream inStream  =   new  FileInputStream(oldPath);  // 读入原文件
151                 FileOutputStream fs  =   new  FileOutputStream(newPath);
152                  byte [] buffer  =   new   byte [ 1444 ];
153                  while  ( (byteread  =  inStream.read(buffer))  !=   - 1 ) {
154                     bytesum  +=  byteread;  // 字节数 文件大小
155                     fs.write(buffer,  0 , byteread);
156                 }
157                 inStream.close();
158                 CheckMethods.PrintDebugMessage( " 复制单个文件操作成功: " + oldPath);
159             }
160         }
161          catch  (Exception e) {
162             CheckMethods.PrintInfoMessage( " 复制单个文件操作出错: " + oldPath);
163             LogHelper.WriteLog(LogHelper.logger_Error, CommonValues.Log_Detail_Level,  " info " " 复制单个文件操作出错: " + oldPath);
164             e.printStackTrace();
165 
166         }
167 
168     }
169 
170      /**
171       * 复制整个文件夹内容
172       *  @param  oldPath String 原文件路径 如:c:/fqf
173       *  @param  newPath String 复制后路径 如:f:/fqf/ff
174       *  @return  boolean
175        */
176      public   void  copyFolder(String oldPath, String newPath) {
177 
178          try  {
179             ( new  File(newPath)).mkdirs();  // 如果文件夹不存在 则建立新文件夹
180             File a = new  File(oldPath);
181             String[] file = a.list();
182             File temp = null ;
183              for  ( int  i  =   0 ; i  <  file.length; i ++ ) {
184                  if (oldPath.endsWith(File.separator)){
185                     temp = new  File(oldPath + file[i]);
186                 }
187                  else {
188                     temp = new  File(oldPath + File.separator + file[i]);
189                 }
190 
191                  if (temp.isFile()){
192                     FileInputStream input  =   new  FileInputStream(temp);
193                     FileOutputStream output  =   new  FileOutputStream(newPath  +   " / "   +
194                             (temp.getName()).toString());
195                      byte [] b  =   new   byte [ 1024   *   5 ];
196                      int  len;
197                      while  ( (len  =  input.read(b))  !=   - 1 ) {
198                         output.write(b,  0 , len);
199                     }
200                     output.flush();
201                     output.close();
202                     input.close();
203                 }
204                  if (temp.isDirectory()){ // 如果是子文件夹
205                     copyFolder(oldPath + " / " + file[i],newPath + " / " + file[i]);
206                 }
207             }
208         }
209          catch  (Exception e) {
210             CheckMethods.PrintInfoMessage( " 复制整个文件夹内容操作出错: " + oldPath + " " + newPath);
211             LogHelper.WriteLog(LogHelper.logger_Error, CommonValues.Log_Detail_Level,  " info " " 复制整个文件夹内容操作出错: " + oldPath + " " + newPath);
212             e.printStackTrace();
213 
214         }
215 
216     }
217 
218      /**
219       * 移动文件到指定目录
220       *  @param  oldPath String 如:c:/fqf.txt
221       *  @param  newPath String 如:d:/fqf.txt
222        */
223      public   void  moveFile(String oldPath, String newPath) {
224         copyFile(oldPath, newPath);
225         delFile(oldPath);
226 
227     }
228 
229      /**
230       * 移动文件到指定目录
231       *  @param  oldPath String 如:c:/fqf.txt
232       *  @param  newPath String 如:d:/fqf.txt
233        */
234      public   void  moveFolder(String oldPath, String newPath) {
235         copyFolder(oldPath, newPath);
236         delFolder(oldPath);
237 
238     }
239  }

 

再来一段压缩的~

 

public   class  ZipHelper {
    
/**   
     * 压缩文件夹  
     * 
@param  zipPath   生成的zip文件路径  
     * 
@param  filePath  需要压缩的文件夹路径  
     * 
@throws  Exception 
     
*/  
    
public   void  zipFolder(String zipPath, String filePath)  throws  Exception {  
        ZipOutputStream out 
=   new  ZipOutputStream( new  FileOutputStream(zipPath));  
        File f 
=   new  File(filePath);  
        zipFiles(out, f, 
"" );  
        out.close();  
    }     

    
/**   
     * 递归调用,压缩文件夹和子文件夹的所有文件  
     * 
@param  out  
     * 
@param  f  
     * 
@param  base  
     * 
@throws  Exception  
     
*/  
    
private   void  zipFiles(ZipOutputStream out, File f, String base)  throws  Exception {  
        
if  (f.isDirectory()) {  
            File[] fl 
=  f.listFiles();  
            out.putNextEntry(
new  ZipEntry(base  +   " / " ));  
            base 
=  base.length()  ==   0   ?   ""  : base  +   " / " ;  
            
for  ( int  i  =   0 ; i  <  fl.length; i ++ ) {  
                zipFiles(out, fl[i], base 
+  fl[i].getName()); // 递归压缩子文件夹  
            }  
        } 
else  {  
            out.putNextEntry(
new  ZipEntry(base));  
            FileInputStream in 
=   new  FileInputStream(f);  
            
int  b;  
            
// System.out.println(base);  
             while  ((b  =  in.read())  !=   - 1 ) {  
                out.write(b);  
            }  
            in.close();  
        }  
    }  
}

 这里的调用方法我没有贴出来,但是函数的参数命名以及注释都已经很清楚了,我相信大家使用起来不成问题,如果遇到了什么问题,随时交流就可以了~

好了今天就这么多内容了,大家慢慢享用吧。

相关文章:

  • Jffs2根文件系统制作[转]
  • 利用JavaScript全选、反选复选按钮
  • JS对外部文件的加载及对IFRMAME的加载的实现,当加载完成后,指定指向方法(方法回调)...
  • 【开发板技术支持】关于real6410 模拟摄像头与real6410 开发板的接线方式图
  • Exchange2010 dag 的部署
  • 常用的ICON图标网站
  • 【学习】HTML5深入学习
  • 关于 CKEditor上传文件时调用ckeditor的技巧
  • windows计数器和瓶颈
  • 华赛防火墙USG2210 L2TP over IPsec×××配置实例
  • Oracle RAC内部错误:ORA-00600[kjbmprlst:shadow]一例
  • 个人起始
  • 浅谈VS编译自定义编译任务—MSBuild Task(csproject)
  • AjaxPro.Net的使用
  • 推荐20个优秀的网页色彩搭配实例
  • Docker 笔记(2):Dockerfile
  • Java 9 被无情抛弃,Java 8 直接升级到 Java 10!!
  • java正则表式的使用
  • JSONP原理
  • mongo索引构建
  • vue自定义指令实现v-tap插件
  • 阿里云容器服务区块链解决方案全新升级 支持Hyperledger Fabric v1.1
  • 从@property说起(二)当我们写下@property (nonatomic, weak) id obj时,我们究竟写了什么...
  • 对象引论
  • 反思总结然后整装待发
  • 分布式事物理论与实践
  • 将 Measurements 和 Units 应用到物理学
  • 微服务入门【系列视频课程】
  • 新书推荐|Windows黑客编程技术详解
  • 一个项目push到多个远程Git仓库
  • 用 Swift 编写面向协议的视图
  • 原生JS动态加载JS、CSS文件及代码脚本
  • 终端用户监控:真实用户监控还是模拟监控?
  • 《码出高效》学习笔记与书中错误记录
  • ​【原创】基于SSM的酒店预约管理系统(酒店管理系统毕业设计)
  • ​低代码平台的核心价值与优势
  • #中国IT界的第一本漂流日记 传递IT正能量# 【分享得“IT漂友”勋章】
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (附源码)spring boot基于小程序酒店疫情系统 毕业设计 091931
  • (官网安装) 基于CentOS 7安装MangoDB和MangoDB Shell
  • (亲测成功)在centos7.5上安装kvm,通过VNC远程连接并创建多台ubuntu虚拟机(ubuntu server版本)...
  • (三维重建学习)已有位姿放入colmap和3D Gaussian Splatting训练
  • (心得)获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
  • (一)使用IDEA创建Maven项目和Maven使用入门(配图详解)
  • (转) SpringBoot:使用spring-boot-devtools进行热部署以及不生效的问题解决
  • (转)ABI是什么
  • (转)JAVA中的堆栈
  • ***通过什么方式***网吧
  • *Django中的Ajax 纯js的书写样式1
  • *setTimeout实现text输入在用户停顿时才调用事件!*
  • .NET CORE 2.0发布后没有 VIEWS视图页面文件
  • .NET CORE使用Redis分布式锁续命(续期)问题
  • .NET 反射的使用
  • .NET/C# 在 64 位进程中读取 32 位进程重定向后的注册表
  • .NET分布式缓存Memcached从入门到实战