在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("获取文件操作权限失败!"); } }