JAVA文件操作工具类(读、增、删除、复制)

使用JAVA的JFinal框架

1.上传文件模型类UploadFile

 1 /**
 2  * Copyright (c) 2011-2017, James Zhan 詹波 ([email protected]).
 3  *
 4  * Licensed under the Apache License, Version 2.0 (the "License");
 5  * you may not use this file except in compliance with the License.
 6  * You may obtain a copy of the License at
 7  *
 8  *      http://www.apache.org/licenses/LICENSE-2.0
 9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.jfinal.upload;
18 
19 import java.io.File;
20 
21 /**
22  * UploadFile.
23  */
24 public class UploadFile {
25     
26     private String parameterName;
27     
28     private String uploadPath;
29     private String fileName;
30     private String originalFileName;
31     private String contentType;
32     
33     public UploadFile(String parameterName, String uploadPath, String filesystemName, String originalFileName, String contentType) {
34         this.parameterName = parameterName;
35         this.uploadPath = uploadPath;
36         this.fileName = filesystemName;
37         this.originalFileName = originalFileName;
38         this.contentType = contentType;
39     }
40     
41     public String getParameterName() {
42         return parameterName;
43     }
44     
45     public String getFileName() {
46         return fileName;
47     }
48     
49     public String getOriginalFileName() {
50         return originalFileName;
51     }
52     
53     public String getContentType() {
54         return contentType;
55     }
56     
57     public String getUploadPath() {
58         return uploadPath;
59     }
60     
61     public File getFile() {
62         if (uploadPath == null || fileName == null) {
63             return null;
64         } else {
65             return new File(uploadPath + File.separator + fileName);
66         }
67     }
68 }
model类

2.文件操作工具类

  1 package eracare.util;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.FileWriter;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.io.InputStreamReader;
 11 import java.io.PrintWriter;
 12 import java.util.StringTokenizer;
 13 /**
 14  * 文件操作工具类
 15  * 读、增、删除、复制
 16  * @author user001
 17  *
 18  */
 19 public class FileOperate {
 20     private String message;
 21     public FileOperate() {
 22     } 
 23     /**
 24      * 读取文本文件内容
 25      * @param filePathAndName 带有完整绝对路径的文件名
 26      * @param encoding 文本文件打开的编码方式
 27      * @return 返回文本文件的内容
 28      */
 29     public String readTxt(String filePathAndName,String encoding) throws IOException{
 30      encoding = encoding.trim();
 31      StringBuffer str = new StringBuffer("");
 32      String st = "";
 33      try{
 34       FileInputStream fs = new FileInputStream(filePathAndName);
 35       InputStreamReader isr;
 36       if(encoding.equals("")){
 37        isr = new InputStreamReader(fs);
 38       }else{
 39        isr = new InputStreamReader(fs,encoding);
 40       }
 41       BufferedReader br = new BufferedReader(isr);
 42       try{
 43        String data = "";
 44        while((data = br.readLine())!=null){
 45          str.append(data+" "); 
 46        }
 47       }catch(Exception e){
 48        str.append(e.toString());
 49       }
 50       st = str.toString();
 51      }catch(IOException es){
 52       st = "";
 53      }
 54      return st;     
 55 }
 56     /**
 57      * 新建目录
 58      * @param folderPath 目录
 59      * @return 返回目录创建后的路径
 60      */
 61     public void createFolder(String folderPath) {
 62 //        String txt = folderPath;
 63         try {
 64             java.io.File myFilePath = new java.io.File(folderPath);
 65 //            txt = folderPath;
 66             if (!myFilePath.exists()) {
 67                 myFilePath.mkdir();
 68             }
 69         }
 70         catch (Exception e) {
 71             message = "创建目录操作出错";
 72         }
 73 //        return txt;
 74     }
 75     
 76     /**
 77      * 多级目录创建
 78      * @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf
 79      * @param paths 无限级目录参数,各级目录以单数线区分 例如 a|b|c
 80      * @return 返回创建文件后的路径 例如 c:myfa c
 81      */
 82     public void createFolders(String folderPath, String paths){
 83         String txts = folderPath;
 84         try{
 85             String txt;
 86             txts = folderPath;
 87             StringTokenizer st = new StringTokenizer(paths,"|");
 88             for(int i=0; st.hasMoreTokens(); i++){
 89                     txt = st.nextToken().trim();
 90                     if(txts.lastIndexOf("/")!=-1){ 
 91                         createFolder(txts+txt);
 92                     }else{
 93                        createFolder(txts+txt+"/");    
 94                     }
 95             }
 96        }catch(Exception e){
 97            message = "创建目录操作出错!";
 98        }
 99 //        return txts;
100     }
101     /**
102      * 新建文件
103      * @param filePathAndName 文本文件完整绝对路径及文件名
104      * @param fileContent 文本文件内容
105      * @return
106      */
107     public void createFile(String filePathAndName, String fileContent) {  
108         try {
109             String filePath = filePathAndName;
110             filePath = filePath.toString();
111             File myFilePath = new File(filePath);
112             if (!myFilePath.exists()) {
113                 myFilePath.createNewFile();
114             }
115             FileWriter resultFile = new FileWriter(myFilePath);
116             PrintWriter myFile = new PrintWriter(resultFile);
117             String strContent = fileContent;
118             myFile.println(strContent);
119             myFile.close();
120             resultFile.close();
121         }
122         catch (Exception e) {
123             message = "创建文件操作出错";
124         }
125     }
126     /**
127      * 有编码方式的文件创建
128      * @param filePathAndName 文本文件完整绝对路径及文件名
129      * @param fileContent 文本文件内容
130      * @param encoding 编码方式 例如 GBK 或者 UTF-8
131      * @return
132      */
133     public void createFile(String filePathAndName, String fileContent, String encoding) {
134      
135         try {
136             String filePath = filePathAndName;
137             filePath = filePath.toString();
138             File myFilePath = new File(filePath);
139             if (!myFilePath.exists()) {
140                 myFilePath.createNewFile();
141             }
142             PrintWriter myFile = new PrintWriter(myFilePath,encoding);
143             String strContent = fileContent;
144             myFile.println(strContent);
145             myFile.close();
146         }
147         catch (Exception e) {
148             message = "创建文件操作出错";
149         }
150     }
151     /**
152      * 删除文件
153      * @param filePathAndName 文本文件完整绝对路径及文件名
154      * @return Boolean 成功删除返回true遭遇异常返回false
155      */
156     public boolean delFile(String filePathAndName) {
157      boolean bea = false;
158         try {
159             String filePath = filePathAndName;
160             File myDelFile = new File(filePath);
161             if(myDelFile.exists()){
162              myDelFile.delete();
163              bea = true;
164             }else{
165              bea = false;
166              message = (filePathAndName+"删除文件操作出错");
167             }
168         }
169         catch (Exception e) {
170             message = e.toString();
171         }
172         return bea;
173     }
174     
175     /**
176      * 删除文件夹
177      * @param folderPath 文件夹完整绝对路径
178      * @return
179      */
180     public void delFolder(String folderPath) {
181         try {
182             delAllFile(folderPath); //删除完里面所有内容
183             String filePath = folderPath;
184             filePath = filePath.toString();
185             java.io.File myFilePath = new java.io.File(filePath);
186             myFilePath.delete(); //删除空文件夹
187         }
188         catch (Exception e) {
189             message = ("删除文件夹操作出错");
190         }
191     }
192         /**
193      * 删除指定文件夹下所有文件
194      * @param path 文件夹完整绝对路径
195      * @return
196      * @return
197      */
198     public boolean delAllFile(String path) {
199      boolean bea = false;
200         File file = new File(path);
201         if (!file.exists()) {
202             return bea;
203         }
204         if (!file.isDirectory()) {
205             return bea;
206         }
207         String[] tempList = file.list();
208         File temp = null;
209         for (int i = 0; i < tempList.length; i++) {
210             if (path.endsWith(File.separator)) {
211                 temp = new File(path + tempList[i]);
212             }else{
213                 temp = new File(path + File.separator + tempList[i]);
214             }
215             if (temp.isFile()) {
216                 temp.delete();
217             }
218             if (temp.isDirectory()) {
219                 delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
220                 delFolder(path+"/"+ tempList[i]);//再删除空文件夹
221                 bea = true;
222             }
223         }
224         return bea;
225     }
226 
227     /**
228      * 复制单个文件
229      * @param oldPathFile 准备复制的文件源
230      * @param newPathFile 拷贝到新绝对路径带文件名
231      * @return
232      */
233     public void copyFile(String oldPathFile, String newPathFile) {
234         try {
235             int bytesum = 0;
236             int byteread = 0;
237             File oldfile = new File(oldPathFile);
238             if (oldfile.exists()) { //文件存在时
239                 InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
240                 FileOutputStream fs = new FileOutputStream(newPathFile);
241                 byte[] buffer = new byte[10485760];
242                 while((byteread = inStream.read(buffer)) != -1){
243                     bytesum += byteread; //字节数 文件大小
244                     fs.write(buffer, 0, byteread);
245                 }
246                 inStream.close();
247             }
248         }catch (Exception e) {
249             message = ("复制单个文件操作出错");
250         }
251     }
252    /**
253      * 复制整个文件夹的内容
254      * @param oldPath 准备拷贝的目录
255      * @param newPath 指定绝对路径的新目录
256      * @return
257      */
258     public void copyFolder(String oldPath, String newPath) {
259         try {
260             new File(newPath).mkdirs(); //如果文件夹不存在 则建立新文件夹
261             File a=new File(oldPath);
262             String[] file=a.list();
263             File temp=null;
264             for (int i = 0; i < file.length; i++) {
265                 if(oldPath.endsWith(File.separator)){
266                     temp=new File(oldPath+file[i]);
267                 }else{
268                     temp=new File(oldPath+File.separator+file[i]);
269                 }
270                 if(temp.isFile()){
271                     FileInputStream input = new FileInputStream(temp);
272                     FileOutputStream output = new FileOutputStream(newPath + "/" +
273                     (temp.getName()).toString());
274                     byte[] b = new byte[1024 * 5];
275                     int len;
276                     while ((len = input.read(b)) != -1) {
277                         output.write(b, 0, len);
278                     }
279                     output.flush();
280                     output.close();
281                     input.close();
282                 }
283                 if(temp.isDirectory()){//如果是子文件夹
284                     copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
285                 }
286             }
287         }catch (Exception e) {
288             message = "复制整个文件夹内容操作出错";
289         }
290     }
291 
292     /**
293      * 移动文件
294      * @param oldPath
295      * @param newPath
296      * @return
297      */
298     public void moveFile(String oldPath, String newPath) {
299         copyFile(oldPath, newPath);
300         delFile(oldPath);
301     }
302     
303     /**
304      * 移动目录
305      * @param oldPath
306      * @param newPath
307      * @return
308      */
309     public void moveFolder(String oldPath, String newPath) {
310         copyFolder(oldPath, newPath);
311         delFolder(oldPath);
312     }
313     public String getMessage(){
314         return this.message;
315     }
316 }
FileOperate类

我写博,主要是为了记录一些自己在工作中遇到的难点、痛点。因为是完成工作后的记录,有一些代码是网上查找的具体出处忘记了。如果代码有什么问题,欢迎大家留言!

猜你喜欢

转载自www.cnblogs.com/KLLQBKY/p/9293154.html
今日推荐