2020年1月15日星期三

Android log应用1:自动删除/data文件夹下面超过五天的文件

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    package="com.example.a0113_log">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"        tools:ignore="ProtectedPermissions" />

    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity3">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
 MainActivity
/**     * 参考:http://www.voidcn.com/article/p-eeswpcan-bpm.html     * 删除超过五天的文件     * @param path     */    private void  del5Days(String path) {
        long fiveDayTime=5L*24L*60L*60L*1000L;  //注意不写L可能导致结果为负数        long currentTime=System.currentTimeMillis();
        File dirFile = new File(path);
        if (dirFile.exists()) {
            File[] files = dirFile.listFiles();
            if (files != null) {
                for (File fileChildDir : files) {
                    //输出文件名或者文件夹名//                    System.out.print(""+fileChildDir.getName());                    if (fileChildDir.isDirectory()) {
                        long lastTime=fileChildDir.lastModified();
                        long diffenTime=currentTime-lastTime;
                        if(diffenTime>fiveDayTime)    //大于五天                        {
                            Log.i(TAG,"del=====>"+path+fileChildDir.getName());
                            try {
                                String tmpPath=path+fileChildDir.getName()+"/";
                                delFiles(tmpPath);
                                fileChildDir.delete();
                                Log.i(TAG,"delete success!");
                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.i(TAG,"delete error"+e.toString());
                            }
                        }
                    }
                    if (fileChildDir.isFile()) {
//                        System.out.println(fileChildDir.getName()+" :  此为文件名");                    }
                }
            }
        }else{
            System.out.println("你想查找的文件不存在");
            return ;
        }
    }

没有评论:

发表评论