Android 处理文件相关调试代码

//删除文件   
 public  void deleteFile(){
    	File file= new File("/data/fielname");
    	if (file.exists() && file.isFile()){
    		boolean deletestatus = file.delete();
    		Log.e("xxxx", " Inside shutdow process delete = "+deletestatus); 
    	}
    }
//创建指定大小文件(较小的文件)
byte[] buffer = new byte[THRESHOLD_MAX_BYTES];
	  int dataWrite = 0;
	  while (dataWrite < THRESHOLD_MAX_BYTES) {
	  out.write(buffer, 0, THRESHOLD_MAX_BYTES);
	  dataWrite++;
}

 

//创建指定大小文件
public static final long BATCHSIZE_MAX_COUNT = 45; //500M
public static boolean createKtefile(String fileName){
        File file = new File(fileName);  
	    if (!file.exists()) {  
	    	try {
	    		boolean created = false;
	    		created = file.createNewFile();
	    		if (!created) {
	    			 Slog.i("xxxx", "createNewFile operation failed for: " + file);
	            }
		    	FileOutputStream  out = new FileOutputStream(file);
		    	try { 
		        	out = new FileOutputStream(file);  
			        FileChannel fileChannel = out.getChannel();  
			        for (int i = 0; i < BATCHSIZE_MAX_COUNT; i++) {  
			            ByteBuffer buffer = ByteBuffer.allocate((int) KET_BATCHSIZE);  
			            fileChannel.write(buffer);  
			        } 
		            Slog.i("xxxx", "createNewFile "+ created);
		            return created;
		        } finally {
		        	out.flush();
	                out.close();
	            }
	        } catch (IOException e){
	       	 Slog.i("xxxx", " Can't create file" + e);
	        }
	    	return false;
	    }
	    Slog.i("xxxx", "file exits not create");
	    return true;
   }
  //删除文件及文件夹  
  public static boolean deleteContentsAndDir(File dir) {
        if (deleteContents(dir)) {
            return dir.delete();
        } else {
            return false;
        }
    }
//删除文件
    public static boolean deleteContents(File dir) {
        File[] files = dir.listFiles();
        boolean success = true;
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    success &= deleteContents(file);
                }
                if (!file.delete()) {
                    Log.w(TAG, "Failed to delete " + file);
                    success = false;
                }
            }
        }
        return success;
    }
//获取系统时间,年月日格式显示当前时间   
public  String getNowTimess(){      
    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
        Date date = new Date(System.currentTimeMillis());      
       return simpleDateFormat.format(date);      
 }
//命令行删除文件及命令执行结果
   Runtime fileRemoval = Runtime.getRuntime();
    String cmdBecomeSu = "su";
    boolean clearCacheSuccess = false;
    try{
    	Process runsum = fileRemoval.exec(cmdBecomeSu);
    	int exitVal = runsum.waitFor();
    	String rmfile = "rm -rf /data/dalvik-cache";
    	Process removal = fileRemoval.exec(rmfile);
    	exitVal = removal.waitFor();
    	if (exitVal == 0) {
    		clearCacheSuccess = true;
    	 }
    } catch ( Exception e){
    		 Slog.e(TAG, "system server init delete dalvik-cache fail" + e);
    }
--------------------------------------------------------------------------------
         
   try {
       Runtime.getRuntime().exec("rm -r /data/piggybank");
    } catch (IOException e) {
       Slog.e(TAG, "system server init delete piggybank fail" + e);
    }
//获取某分区的可用空间大小  
//如例:MTKlOG APP获取内部存储空间的可用空间,三次机会获取
  /**
     * Get the remaining storage size in the given file path.
     *
     * @param storagePath
     *            String
     * @return remaining size in MB
     */
    public static int getAvailableStorageSize(String storagePath) {
        StatFs stat;
        int retryNum = 1;
        while (retryNum <= 3) {
            try {
                stat = new StatFs(storagePath);
                long blockSize = stat.getBlockSizeLong();
                long availableBlocks = stat.getAvailableBlocksLong();
                int availableSize = (int) (availableBlocks * blockSize / (1024 * 1024));
                Utils.logd(TAG, "-->getAvailableStorageSize(), path=" + storagePath + ", size="
                        + availableSize + "MB");
                return availableSize;
            } catch (IllegalArgumentException e) {
                Utils.logw(TAG, "Fail to get storage info from [" + storagePath
                        + "] by StatFs, try again(index=" + retryNum + ").");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            retryNum++;
        }
        Utils.loge(TAG, "-->getAvailableStorageSize(), fail to get it by StatFs,"
                + " unknown exception happen.");
        return 0;
    }

 

//获取一个文件夹或文件的大小    
public static long getFileSize(String filePath) {
        long size = 0;
        if (filePath == null) {
            return 0;
        }
        File fileRoot = new File(filePath);
        if (fileRoot == null || !fileRoot.exists()) {
            return 0;
        }
        if (!fileRoot.isDirectory()) {
            size = fileRoot.length();
        } else {
            File[] files = fileRoot.listFiles();
            // why get a null here ?? maybe caused by permission denied
            if (files == null || files.length == 0) {
                Utils.logv(TAG, "Loop folder [" + filePath + "] get a null/empty list");
                return 0;
            }
            for (File file : files) {
                if (file == null) {
                    continue;
                }
                size += getFileSize(file.getAbsolutePath());
            }
        }
        return size;
    }
//复制一个目录下的所有文件到另一个目录下
/**
     * @param sourceFilePath
     *            String
     * @param targetFilePath
     *            String
     * @return boolean
     */
    public static boolean doCopy(String sourceFilePath, String targetFilePath) {
        Utils.logi(TAG, "-->doCopy() from " + sourceFilePath + " to " + targetFilePath);
        File sourceFile = new File(sourceFilePath);
        if (null == sourceFile || !sourceFile.exists()) {
            Utils.logw(TAG,"The sourceFilePath = " + sourceFilePath + " is not existes, do copy failed!");
            return false;
        }
        // Get all files and sub directories under the current directory
        File[] files = sourceFile.listFiles();
        if (null == files) {
            // Current file is not a directory
            String tagLogPath = sourceFile.getAbsolutePath();
            return copyFile(tagLogPath, targetFilePath);
        } else {
            // Current file is a directory
            File targetFile = new File(targetFilePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            for (File subFile : files) {
                doCopy(subFile.getAbsolutePath(),
                        targetFilePath + File.separator + subFile.getName());
            }
        }
        return true;
    }

    private static final int COPY_BUFFER_SIZE = 1024;

    private static boolean copyFile(String sourceFilePath, String targetFilePath) {
        Utils.logi(TAG, "-->copyFile() from " + sourceFilePath + " to " + targetFilePath);
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            Utils.logw(TAG, "The sourceFilePath = " + sourceFilePath + " is not existes, do copy failed!");
            return false;
        }

        File targetFile = new File(targetFilePath);
        if (targetFile.exists()) {
            targetFile.delete();
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File parentFile = targetFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            targetFile.createNewFile();
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(targetFile);
            if (fos == null) {
                return false;
            }
            byte[] temp = new byte[COPY_BUFFER_SIZE];
            int len;
            while ((len = fis.read(temp)) != -1) {
                fos.write(temp, 0, len);
            }
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值