本地打印log

      Gson gson = new Gson();
                        List<String> list = new ArrayList<>();
                        if (ACache.get(getApplicationContext()).getAsString("PhotoScreenLog") != null) {
                            list = gson.fromJson(ACache.get(getApplicationContext()).getAsString("PhotoScreenLog"), new TypeToken<List<String>>() {
                            }.getType());
                        }
                        list.add("/samingFuse/" + dirname + "/" + dirName + "/" + picdir);
                        String data = gson.toJson(list);
                        ACache.get(getApplicationContext()).put("PhotoScreenLog", data);
                        FileUtil.saveFile(data, Environment.getExternalStorageDirectory() + "/HomeCloud/", "PhotoScreenLog.txt");
                  
FileUtil工具类

 

public class FileUtil {

    /**
     * SD卡的状态
     */
    public static final String SDCARDSTATE = Environment.getExternalStorageState();

    /**
     * 文件在SD卡中存储的根路径
     */
    public static final String SDCARDPATH = Environment.getExternalStorageDirectory().getPath();

    /**
     * 获取包名下files的路径
     *
     * @param context
     * @return 包名/files
     */
    public static String getFilePath(Context context) {
        return context.getApplicationContext().getFilesDir().getPath();
    }

    public static String getCahePath(Context context) {
        return context.getApplicationContext().getCacheDir().getPath();
    }

    /**
     * 保存文件
     *
     * @param data     数据内容
     * @param path     绝对路径
     * @param fileName 文件名
     * @return true 保存成功,false 保存失败
     */
    public static boolean saveFile(String data, String path, String fileName) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        file = new File(file, fileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            out.write(data.getBytes());
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 读取文件
     *
     * @param path 文件路径
     * @return
     */
    public static String readFile(String path) {
        File file = new File(path);
        if (!file.isFile()) {
            try {
                throw new Exception("it's not a file,please check!");
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        StringBuffer sb = new StringBuffer();
        try {
            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[in.available()];
            int read = in.read(b);
            while (read != -1) {
                sb.append(new String(b));
                read = in.read(b);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sb.toString();
    }


    /**
     * 删除路径下的:文件和文件夹,包括当前文件夹
     *
     * @param absoluteFilePath :绝对路径
     * @return true:删除成功,false:删除失败
     * 注意:当前路径不存在时,也返回true
     */
    public static boolean deleteFile(String absoluteFilePath) {
        File file = new File(absoluteFilePath);
        try {
            if (!file.exists()) {
                return true;
            }
            if (file.isFile()) {
                file.delete();
                return true;
            }
            if (!absoluteFilePath.endsWith(File.separator)) {
                absoluteFilePath = absoluteFilePath + File.separator;
            }
            if (file.isDirectory()) {
                if (file.listFiles().length == 0) {
                    file.delete();
                } else {
                    File[] files = file.listFiles();
                    for (File dirFile : files) {
                        deleteFile(dirFile.getAbsolutePath());
                    }
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public static boolean saveToCahe(String data, String dir, String fileName, Context context) {
        String path = getCahePath(context) + dir;
        return saveFile(data, path, fileName);
    }

    public static String readFromCahe(String dir, Context context) {
        String path = getCahePath(context) + dir;
        return readFile(path);
    }

    public static boolean deleteInCache(String dir, Context context) {
        String path = getCahePath(context) + dir;
        return deleteFile(path);
    }

    public static boolean clearCache(Context context) {
        return deleteFile(getCahePath(context));
    }


    /**
     * 将文件保存到应用包名/files目录下
     *
     * @param data     要保存的内容
     * @param dir      保存的相对路径,不包括文件名:"/myproject/function1/aa"
     * @param fileName 文件名称:"1.txt"
     * @return
     */
    public static boolean saveToFile(String data, String dir, String fileName, Context context) {
        String path = getFilePath(context) + dir;
        return saveFile(data, path, fileName);
    }

    /**
     * 从应用包名/files目录下读取文件
     *
     * @param dir     :"/dd/1.txt"
     * @param context
     * @return
     */
    public static String readFromFile(String dir, Context context) {
        String path = getFilePath(context) + dir;
        return readFile(path);
    }

    public static boolean deleteInFile(String dir, Context context) {
        String path = getFilePath(context) + dir;
        return deleteFile(path);
    }

    /**
     * 保存数据到SD卡上,
     *
     * @param data:要保存的数据内容
     * @param dir:文件的相对路径,"/aa/bb"
     * @param fileName:文件名,"1.txt"
     * @return boolean 是否保存成功,true保存成功,false保存失败
     */
    public static boolean saveToSDCard(String data, String dir, String fileName) {
        if (!Environment.MEDIA_MOUNTED.equals(SDCARDSTATE)) {
            try {
                throw new Exception("SDCard state error");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return saveFile(data, SDCARDPATH + dir, fileName);
    }

    /**
     * @param dir 文件在sd卡中的路径:"/bb/dd/1.txt"
     * @return String 文件内容
     */
    public static String getFromSDCard(String dir) {
        String path = SDCARDPATH + dir;
        return readFile(path);
    }


    /**
     * 从SD卡上删除文件
     *
     * @param path
     * @return 是否删除文件成功
     */
    public static boolean deleteFileInSDCard(String path) {
        return deleteFile(path);
    }

    /**
     * 将图片二进制转换成file
     */
    public static File byteToFile(byte[] byteArray, String pathName) throws IOException {
        File file = new File(pathName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(byteArray);
        fos.flush();
        fos.close();
        return file;
    }

    /**
     * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
     *
     * @param context
     * @param imageUri
     */
    @TargetApi(19)
    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 获得指定文件的byte数组
     *
     * @param filePath 文件绝对路径
     * @return
     */
    public static byte[] fileToByte(String filePath) {
        ByteArrayOutputStream bos = null;
        BufferedInputStream in = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException("file not exists");
            }
            bos = new ByteArrayOutputStream((int) file.length());
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件名称
     */
    public static String getFileName(String filePath) {
        Log.i("filePath", filePath);
        int start = filePath.lastIndexOf("/");
//        int end = filePath.lastIndexOf(".");
        if (start != -1 && filePath.length() != -1) {
            return filePath.substring(start + 1, filePath.length());
        } else {
            return null;
        }
    }

    /**
     * 获取并计算文件大小
     */
    public static String getFileSizePath(String filePath) {
        long size = 0;
        File file = new File(filePath);
        if (file.exists()) {
            size = file.length();
        }
        return getFileSize(size);
    }


    /**
     * 获取并计算文件大小
     */
    public static String getFileSize(long fileSize) {
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String fileSizeString;
        int GB = 1024 * 1024 * 1024;
        int MB = 1024 * 1024;
        int KB = 1024;

        if (fileSize / GB >= 1) {
            fileSizeString = decimalFormat.format(fileSize / (float) GB) + "GB";
        } else if (fileSize / MB >= 1) {
            fileSizeString = decimalFormat.format(fileSize / (float) MB) + "MB";
        } else if (fileSize / KB >= 1) {
            fileSizeString = decimalFormat.format(fileSize / (float) KB) + "KB";
        } else {
            fileSizeString = fileSize + "B";
        }
        return fileSizeString;
    }

    /**
     * 获取文件扩展名
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot);
            }
        }
        return filename;
    }

    /**
     * 判断当前文件的类型
     *
     * @param suffixName
     */
    public static String getFileType(String suffixName) {
        String[] photo = {".tif", ".tiff", ".jpg", ".jpeg", ".gif", ".png", ".bmp", ".ico", ".heic", ".psd", ".raw",
                ".TIF", ".TIFF", ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP", ".ICO", ".HEIC", ".PSD", ".RAW"};
        String[] documents = {".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".pdf", ".wps",
                ".DOC", ".DOCX", ".XLS", ".XLSX", ".PPT", ".PPTX", ".TXT", ".PDF", ".WPS"};
        String[] music = {".mp3", ".wav", ".wma", ".ogg", ".ape", ".flac", ".aac", ".m4a",
                ".MP3", ".WAV", ".WMA", ".OGG", ".APE", ".FLAC", ".AAC", ".M4A"};
        String[] video = {".rm", ".rmvb", ".mpg", ".mpeg", ".3gp", ".mov", ".mp4", ".m4v", ".avi", ".dat", ".mkv", ".flv", ".vob", ".wmv",
                ".RM", ".RMVB", ".MPG", ".MPEG", ".3GP", ".MOV", ".MP4", ".M4V", ".AVI", ".DAT", ".MKV", ".FLV", ".VOB", ".WMV"};
        if (Arrays.asList(photo).contains(suffixName)) {
            return "图片";
        } else if (Arrays.asList(documents).contains(suffixName)) {
            return "文档";
        } else if (Arrays.asList(music).contains(suffixName)) {
            return "音乐";
        } else if (Arrays.asList(video).contains(suffixName)) {
            return "视频";
        } else {
            return "其他";
        }
    }

    /**
     * 将Url拼接的参数转换为UTF-8
     */
    public static String toUTF8(String params) {
        try {
            params = URLEncoder.encode(params, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * 获取mac地址
     */
    public static String getMac() {
        String macId;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            macId = MacUtils.getAndroid7MAC();
        } else {
            macId = MacUtils.getMacOneSix();
        }
        return macId;
    }

    public static String getFileMimeType(String path) {
        String suffix = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
        if (suffix.length() == 0) {
            return "application/octet-stream";
        } else {
            String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
            if (mime != null) {
                return mime;
            } else {
                return "application/octet-stream";
            }
        }
    }

    /**
     * 时间戳转换成时间
     */
    public static String getConvertToDate(long mtime) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date = new Date(mtime * 1000);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 将数据处理好,发送给后台
     */
    public static StringBuilder setParametersIntoString(List<String> fileNameList) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < fileNameList.size(); i++) {
            if (i == fileNameList.size() - 1) {
                stringBuilder.append(fileNameList.get(i));
            } else {
                stringBuilder.append(fileNameList.get(i));
                stringBuilder.append(":");
            }
        }
        return stringBuilder;
    }

    /**
     * 解压到指定目录
     *
     * @param zipPath
     * @param descDir
     */
    public static void unZipFiles(String zipPath, String descDir) throws IOException {
        unZipFiles(new File(zipPath), descDir);
    }

    /**
     * 解压文件到指定目录
     * 解压后的文件名,和之前一致
     *
     * @param zipFile 待解压的zip文件
     * @param descDir 指定目录
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFiles(File zipFile, String descDir) throws IOException {
        ZipFile zip = new ZipFile(zipFile);//解决中文文件夹乱码
        File pathFile = new File(zipFile.getAbsolutePath());
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = ("HomeCloud/" + zipEntryName).replaceAll("\\*", "/");

            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }

            FileOutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        return;
    }

    public static String getCurrentUploadDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        return format.format(date);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值