Android-----File(文件各種操作)


在Android編程中,操作文件是基本的必備技能,現在做一個操作文件的小工具:DocumentTool.java

代碼如下:

  1 package com.hs.example.exampleapplication.ToolUtil;
  2 
  3 import android.app.Activity;
  4 import android.content.Context;
  5 import android.content.pm.PackageManager;
  6 import android.content.res.AssetManager;
  7 import android.os.Environment;
  8 import android.support.v4.app.ActivityCompat;
  9 import android.text.TextUtils;
 10 import android.util.Log;
 11 
 12 import java.io.File;
 13 import java.io.FileInputStream;
 14 import java.io.FileOutputStream;
 15 import java.io.InputStream;
 16 import java.io.OutputStream;
 17 import java.io.RandomAccessFile;
 18 
 19 /**
 20  * Created by 98426 on 2019/4/17.
 21  */
 22 
 23 public class DocumentTool {
 24 
 25     /**
 26      * 【動態申請SD卡讀寫的權限】
 27      * Android6.0之后系統對權限的管理更加嚴格了,不但要在AndroidManifest中添加,還要在應用運行的時候動態申請
 28      * **/
 29     private static final int REQUEST_EXTERNAL_STORAGE = 1 ;
 30     private static String[] PERMISSON_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
 31             "android.permission.WRITE_EXTERNAL_STORAGE"};
 32     public static void verifyStoragePermissions(Activity activity){
 33         try {
 34             int permission = ActivityCompat.checkSelfPermission(activity,"android.permission.WRITE_EXTERNAL_STORAGE");
 35             if(permission!= PackageManager.PERMISSION_GRANTED){/**【判斷是否已經授予權限】**/
 36                 ActivityCompat.requestPermissions(activity,PERMISSON_STORAGE,REQUEST_EXTERNAL_STORAGE);
 37             }
 38         }catch (Exception e){
 39             e.printStackTrace();
 40         }
 41     }
 42 
 43     /**【檢查文件目錄是否存在,不存在就創建新的目錄】**/
 44     public static void checkFilePath(File file ,boolean isDir){
 45         if(file!=null){
 46             if(!isDir){     //如果是文件就返回父目錄
 47                 file = file.getParentFile();
 48             }
 49             if(file!=null && !file.exists()){
 50                 file.mkdirs();
 51             }
 52         }
 53     }
 54 
 55     /**【創建一個新的文件夾】**/
 56     public static void addFolder(String folderName){
 57         try {
 58             if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
 59                 File sdCard = Environment.getExternalStorageDirectory();
 60                 File newFolder = new File(sdCard + File.separator + folderName);
 61                 if(!newFolder.exists()){
 62                     boolean isSuccess = newFolder.mkdirs();
 63                     Log.i("TAG:","文件夾創建狀態--->" + isSuccess);
 64                 }
 65                 Log.i("TAG:","文件夾所在目錄:" + newFolder.toString());
 66             }
 67         }catch (Exception e){
 68             e.printStackTrace();
 69         }
 70     }
 71 
 72     /**【創建文件】**/
 73     public static void addFile(String fileName){
 74         if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
 75             try {
 76                 File sdCard = Environment.getExternalStorageDirectory();
 77                 File newFile = new File(sdCard.getCanonicalPath()+File.separator+"testFolder/"+fileName);
 78                 if(!newFile.exists()){
 79                     boolean isSuccess = newFile.createNewFile();
 80                     Log.i("TAG:","文件創建狀態--->"+isSuccess);
 81                     Log.i("TAG:","文件所在路徑:"+newFile.toString());
 82                     deleteFile(newFile);
 83                 }
 84             }catch (Exception e){
 85                 e.printStackTrace();
 86             }
 87         }
 88     }
 89 
 90     /**【刪除文件】**/
 91     public static void deleteFile(File file){
 92         if(file.exists()){                          //判斷文件是否存在
 93             if(file.isFile()){                      //判斷是否是文件
 94                 boolean isSucess = file.delete();
 95                 Log.i("TAG:","文件刪除狀態--->" + isSucess);
 96             }else if(file.isDirectory()){           //判斷是否是文件夾
 97                 File files[] = file.listFiles();    //聲明目錄下所有文件
 98                 for (int i=0;i<files.length;i++){   //遍歷目錄下所有文件
 99                     deleteFile(files[i]);           //把每個文件迭代刪除
100                 }
101                boolean isSucess = file.delete();
102                 Log.i("TAG:","文件夾刪除狀態--->" + isSucess);
103             }
104         }
105     }
106 
107     /**【重寫數據到文件】**/
108     public static void writeData(String path , String fileData){
109         try {
110             if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
111                 File file = new File(path);
112                 FileOutputStream out = new FileOutputStream(file,false);
113                 out.write(fileData.getBytes("UTF-8"));              //將數據寫入到文件中
114                 Log.i("TAG:","將數據寫入到文件中:"+fileData);
115                 out.close();
116             }
117         }catch (Exception e){
118             e.printStackTrace();
119         }
120     }
121 
122     /**【續寫數據到文件】**/
123     public static void writtenFileData(String path , String data){
124         try {
125             if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
126                 File file = new File(path);
127                 RandomAccessFile raf = new RandomAccessFile(file,"rw");  //按讀寫方式
128                 raf.seek(file.length());                                        //將文件指針移到文件尾
129                 raf.write(data.getBytes("UTF-8"));                //將數據寫入到文件中
130                 Log.i("TAG:","要續寫進去的數據:" + data);
131                 raf.close();
132             }
133         }catch (Exception e){
134             e.printStackTrace();
135         }
136     }
137 
138     /**【讀取文件內容】**/
139     public static String readFileContent(String path){
140         try {
141             if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
142                 File file = new File(path);
143                 byte [] buffer = new byte[32*1024];
144                 FileInputStream fis = new FileInputStream(file);
145                 int len = 0;
146                 StringBuffer sb = new StringBuffer("");
147                 while((len=fis.read(buffer))>0){
148                     sb.append(new String(buffer,0,len));
149                 }
150                 fis.close();
151                 return sb.toString();
152             }
153         }catch (Exception e){
154             e.printStackTrace();
155         }
156         return null;
157     }
158 
159     /**【判斷文件是否存在】**/
160     public static boolean isFileExists(String fileName){
161         File file = new File(fileName);
162         return file.exists();
163     }
164 
165     /**【判斷文件夾是否存在】**/
166     public static boolean isFolderExists(String directoryPath){
167         if(TextUtils.isEmpty(directoryPath)){
168             return false;
169         }
170         File dire = new File(directoryPath);
171         return (dire.exists() && dire.isDirectory());  //如果是文件夾並且文件夾存在則返回true
172     }
173 
174     /**【獲取文件夾名稱】**/
175     public static String getFolderName(String folderName){
176         if(TextUtils.isEmpty(folderName)){
177             return folderName;
178         }
179         int filePosi = folderName.lastIndexOf(File.separator);
180         return (filePosi == -1 ) ? "" : folderName.substring(0 , filePosi);
181     }
182 
183     /**【重命名文件】**/
184     public static boolean renameFile(String oldFileName , String newFileName){
185         File oldName = new File(oldFileName);
186         File newName = new File(newFileName);
187         return oldName.renameTo(newName);
188     }
189 
190     /**【判斷文件夾里是否有文件】**/
191     public static boolean hasFileExists(String folderPath){
192         File file = new File(folderPath);
193         if(file.exists()){
194             File [] files = file.listFiles();
195             if(files.length>0){
196                 return true;
197             }
198         }
199         return false;
200     }
201 
202     /**【復制文件】參數為:String **/
203     public static int copyFile(String fromFile , String toFile){
204         try {
205             InputStream fosfrom = new FileInputStream(fromFile);
206             OutputStream outto = new FileOutputStream(toFile);
207             byte[] bt = new byte[1024];
208             int len = fosfrom.read(bt);
209             if(len > 0){
210                 outto.write(bt,0,len);
211             }
212             fosfrom.close();
213             outto.close();
214             return 0;
215         }catch (Exception e){
216             e.printStackTrace();
217             return -1;
218         }
219     }
220     /**【復制文件】參數為:File  **/
221     public static int copyFile(File formFile , File toFile){
222         try {
223             InputStream forform = new FileInputStream(formFile);
224             OutputStream forto = new FileOutputStream(toFile);
225             byte [] bt = new byte[1024];
226             int len = forform.read(bt);
227             if(len > 0){
228                 forto.write(bt,0,len);
229             }
230             forform.close();
231             forto.close();
232             return 0;
233         }catch (Exception e){
234             e.printStackTrace();
235             return -1;
236         }
237     }
238     /**【復制文件】使用:AssetManager  **/
239     public static void copyFileFormAsset(Context context,String assetFile , String toFilePath){
240         if(!new File(toFilePath).exists()){
241             try {
242                 AssetManager assetManager = context.getAssets();
243                 InputStream is = assetManager.open(assetFile);
244                 OutputStream os = new FileOutputStream(new File(toFilePath));
245                 byte [] bt = new byte[1024];
246                 int len = 0;
247                 while ((is.read(bt))>0){        //循環從輸入流讀取
248                     os.write(bt,0,len);     //將讀取到的輸入流寫到輸出流
249                 }
250                 is.close();
251                 os.close();
252             }catch (Exception e){
253                 e.printStackTrace();
254             }
255         }
256     }
257 
258     /**【復制文件夾】**/
259     public static int copyDir(String fromFolder , String toFolder){
260         File [] currentFiles;
261         File root = new File(fromFolder);
262         if(!root.exists()){                     //如果文件不存在就返回出去
263             return -1;
264         }
265         currentFiles = root.listFiles();        //存在則獲取當前目錄下的所有文件
266         File targetDir = new File(toFolder);    //目標目錄
267         if(!targetDir.exists()){                //不存在就創建新目錄
268             targetDir.mkdirs();
269         }
270         for(int i=0;i<currentFiles.length;i++){ //遍歷currentFiles下的所有文件
271             if(currentFiles[i].isDirectory()){  //如果當前目錄為子目錄
272                 copyDir(currentFiles[i].getPath() + "/" , currentFiles[i].getName()+"/");  /**進行當前函數遞歸操作**/
273             }else{                              //當前為文件,則進行文件拷貝
274                 copyFile(currentFiles[i].getPath() , toFolder + currentFiles[i].getName());
275             }
276         }
277         return 0;
278     }
279 
280 }

 

接下來直接調用以上方法就可以了:

 

 1 public class MainActivity extends AppCompatActivity implements View.OnClickListener{
 2 
 3   Button  btn_file ;
 4 
 5   @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9 
10         /**【動態申請sdCard讀寫權限】**/
11         DocumentTool.verifyStoragePermissions(MainActivity.this);
12 
13 
14         btn_file = this.findViewById(R.id.btn_file);
15         btn_file.setOnClickListener(this);
16 
17     }
18 
19    @Override
20     public void onClick(View view) {
21         int id = view.getId();
22         switch (id){
23             case R.id.btn_file:
24                 File_i_u_d_s();
25                 break;
26         }
27     }
28 
29 /**【操作文件的方法】**/
30     private void File_i_u_d_s(){
31         DocumentTool tool = new DocumentTool();
32 
33         /**【新建文件夾】**/
34        /* String folderName = "testFolder";
35         tool.addFolder(folderName);*/
36 
37         /**【新建文件】**/
38         /*tool.addFile("testFile2");*/
39 
40         /**【重寫數據到文件下面】**/
41         /*String path ="/storage/emulated/0/testFolder/testFile";
42         String data ="123456789";
43         tool.writeData(path,data);*/
44 
45         /**【續寫數據到文件中】**/
46         /*String path ="/storage/emulated/0/testFolder/testFile";
47         String data ="000";
48         tool.writtenFileData(path,data);*/
49 
50         /**【讀取文件中的數據】**/
51        /* String path ="/storage/emulated/0/testFolder/testFile";
52         String data = tool.readFileContent(path);
53         Log.i("TAG:","文件中拿到的數據:"+data);*/
54 
55        String path = Environment.getExternalStorageDirectory().toString();
56        Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
57 
58     }
59 }    

運行結果就不發上來了,如有更好改進方法歡迎留言指正。

刪除指定文件夾下 n 天前的文件

/*
    * 刪除文件,獲取文件時間與當前時間對比,刪除dayNum天前文件
    * */

    public static void removeFileByTime(String dirPath , int dayNum){
        //獲取目錄下所有文件
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            List<File> allFile = getDirAllFile(new File(dirPath));      //獲取指定目錄下所有文件
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date end = new Date(System.currentTimeMillis());//獲取當前時間
            try {
                end = dateFormat.parse(dateFormat.format(end));
                for (File file : allFile){
                    //文件時間
                    Date star = dateFormat.parse(dateFormat.format(new Date(file.lastModified())));
                    long diff = end.getTime() - star.getTime();//當前時間減去文件時間
                    long days = diff / (1000 * 60 * 60 * 24);//一天
                    if (days > dayNum){
                        deleteFileByTime(file);
                        Log.e("刪除:","成功!");
                    }
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }else {
            ToastUtil.showAnimaToast("獲取文件操作權限失敗!");
        }

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM