效果图:
?
?
?
?
关于Android文件存储路径:
参考:彻底搞懂Android文件存储---内部存储,外部存储以及各种存储路径解惑_ 雨季莫忧离的博客-CSDN博客
1、Environment.getDataDirectory() = /data 这个方法是获取内部存储的根路径 2、getFilesDir().getAbsolutePath() = /data/user/0/packname/files 这个方法是获取某个应用在内部存储中的files路径 3、getCacheDir().getAbsolutePath() = /data/user/0/packname/cache 这个方法是获取某个应用在内部存储中的cache路径 4、getDir(“myFile”, MODE_PRIVATE).getAbsolutePath() = /data/user/0/packname/app_myFile 这个方法是获取某个应用在内部存储中的自定义路径 方法2,3,4的路径中都带有包名,说明他们是属于某个应用 ………………………………………………………………………………………… 5、Environment.getExternalStorageDirectory().getAbsolutePath() = /storage/emulated/0 这个方法是获取外部存储的根路径 6、Environment.getExternalStoragePublicDirectory(“”).getAbsolutePath() = /storage/emulated/0 这个方法是获取外部存储的根路径 7、getExternalFilesDir(“”).getAbsolutePath() = /storage/emulated/0/Android/data/packname/files 这个方法是获取某个应用在外部存储中的files路径 8、getExternalCacheDir().getAbsolutePath() = /storage/emulated/0/Android/data/packname/cache 这个方法是获取某个应用在外部存储中的cache路径
先安利一个GitHub的Android工具类代码集合:AndroidUtilCode/README-CN.md at master · Blankj/AndroidUtilCode · GitHub
感兴趣的可以去看看,个人感觉很好用,已经star了~
压缩文件成zip的工具类就是在上面扒下来的:
建议直接用我这个类,后面加了几个获取所有文件名的方法。
ZipUtils.class:
package cnwy.xda.threedpolygontest.utils;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/27
* desc : utils about zip
* </pre>
*/
public final class ZipUtils {
private static final int BUFFER_LEN = 8192;
private ZipUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Zip the files.
*
* @param srcFiles The source of files.
* @param zipFilePath The path of ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<String> srcFiles,
final String zipFilePath)
throws IOException {
return zipFiles(srcFiles, zipFilePath, null);
}
/**
* Zip the files.
*
* @param srcFilePaths The paths of source files.
* @param zipFilePath The path of ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<String> srcFilePaths,
final String zipFilePath,
final String comment)
throws IOException {
if (srcFilePaths == null || zipFilePath == null) return false;
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (String srcFile : srcFilePaths) {
if (!zipFile(getFileByPath(srcFile), "", zos, comment)) return false;
}
return true;
} finally {
if (zos != null) {
zos.finish();
zos.close();
}
}
}
/**
* Zip the files.
*
* @param srcFiles The source of files.
* @param zipFile The ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<File> srcFiles, final File zipFile)
throws IOException {
return zipFiles(srcFiles, zipFile, null);
}
/**
* Zip the files.
*
* @param srcFiles The source of files.
* @param zipFile The ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<File> srcFiles,
final File zipFile,
final String comment)
throws IOException {
if (srcFiles == null || zipFile == null) return false;
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
for (File srcFile : srcFiles) {
if (!zipFile(srcFile, "", zos, comment)) return false;
}
return true;
} finally {
if (zos != null) {
zos.finish();
zos.close();
}
}
}
/**
* Zip the file.
*
* @param srcFilePath The path of source file.
* @param zipFilePath The path of ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final String srcFilePath,
final String zipFilePath)
throws IOException {
return zipFile(getFileByPath(srcFilePath), getFileByPath(zipFilePath), null);
}
/**
* Zip the file.
*
* @param srcFilePath The path of source file.
* @param zipFilePath The path of ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final String srcFilePath,
final String zipFilePath,
final String comment)
throws IOException {
return zipFile(getFileByPath(srcFilePath), getFileByPath(zipFilePath), comment);
}
/**
* Zip the file.
*
* @param srcFile The source of file.
* @param zipFile The ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final File srcFile,
final File zipFile)
throws IOException {
return zipFile(srcFile, zipFile, null);
}
/**
* Zip the file.
*
* @param srcFile The source of file.
* @param zipFile The ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final File srcFile,
final File zipFile,
final String comment)
throws IOException {
if (srcFile == null || zipFile == null) return false;
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
return zipFile(srcFile, "", zos, comment);
} finally {
if (zos != null) {
zos.close();
}
}
}
private static boolean zipFile(final File srcFile,
String rootPath,
final ZipOutputStream zos,
final String comment)
throws IOException {
rootPath = rootPath + (isSpace(rootPath) ? "" : File.separator) + srcFile.getName();
if (srcFile.isDirectory()) {
File[] fileList = srcFile.listFiles();
if (fileList == null || fileList.length <= 0) {
ZipEntry entry = new ZipEntry(rootPath + '/');
entry.setComment(comment);
zos.putNextEntry(entry);
zos.closeEntry();
} else {
for (File file : fileList) {
if (!zipFile(file, rootPath, zos, comment)) return false;
}
}
} else {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(srcFile));
ZipEntry entry = new ZipEntry(rootPath);
entry.setComment(comment);
zos.putNextEntry(entry);
byte buffer[] = new byte[BUFFER_LEN];
int len;
while ((len = is.read(buffer, 0, BUFFER_LEN)) != -1) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
} finally {
if (is != null) {
is.close();
}
}
}
return true;
}
/**
* Unzip the file.
*
* @param zipFilePath The path of ZIP file.
* @param destDirPath The path of destination directory.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFile(final String zipFilePath,
final String destDirPath)
throws IOException {
return unzipFileByKeyword(zipFilePath, destDirPath, null);
}
/**
* Unzip the file.
*
* @param zipFile The ZIP file.
* @param destDir The destination directory.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFile(final File zipFile,
final File destDir)
throws IOException {
return unzipFileByKeyword(zipFile, destDir, null);
}
/**
* Unzip the file by keyword.
*
* @param zipFilePath The path of ZIP file.
* @param destDirPath The path of destination directory.
* @param keyword The keyboard.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFileByKeyword(final String zipFilePath,
final String destDirPath,
final String keyword)
throws IOException {
return unzipFileByKeyword(getFileByPath(zipFilePath), getFileByPath(destDirPath), keyword);
}
/**
* Unzip the file by keyword.
*
* @param zipFile The ZIP file.
* @param destDir The destination directory.
* @param keyword The keyboard.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFileByKeyword(final File zipFile,
final File destDir,
final String keyword)
throws IOException {
if (zipFile == null || destDir == null) return null;
List<File> files = new ArrayList<>();
ZipFile zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
try {
if (isSpace(keyword)) {
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName().replace("\\", "/");
if (entryName.contains("../")) {
Log.e("ZipUtils", "entryName: " + entryName + " is dangerous!");
continue;
}
if (!unzipChildFile(destDir, files, zip, entry, entryName)) return files;
}
} else {
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName().replace("\\", "/");
if (entryName.contains("../")) {
Log.e("ZipUtils", "entryName: " + entryName + " is dangerous!");
continue;
}
if (entryName.contains(keyword)) {
if (!unzipChildFile(destDir, files, zip, entry, entryName)) return files;
}
}
}
} finally {
zip.close();
}
return files;
}
private static boolean unzipChildFile(final File destDir,
final List<File> files,
final ZipFile zip,
final ZipEntry entry,
final String name) throws IOException {
File file = new File(destDir, name);
files.add(file);
if (entry.isDirectory()) {
return createOrExistsDir(file);
} else {
if (!createOrExistsFile(file)) return false;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(zip.getInputStream(entry));
out = new BufferedOutputStream(new FileOutputStream(file));
byte buffer[] = new byte[BUFFER_LEN];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
return true;
}
/**
* Return the files' path in ZIP file.
*
* @param zipFilePath The path of ZIP file.
* @return the files' path in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getFilesPath(final String zipFilePath)
throws IOException {
return getFilesPath(getFileByPath(zipFilePath));
}
/**
* Return the files' path in ZIP file.
*
* @param zipFile The ZIP file.
* @return the files' path in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getFilesPath(final File zipFile)
throws IOException {
if (zipFile == null) return null;
List<String> paths = new ArrayList<>();
ZipFile zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
String entryName = ((ZipEntry) entries.nextElement()).getName().replace("\\", "/");;
if (entryName.contains("../")) {
Log.e("ZipUtils", "entryName: " + entryName + " is dangerous!");
paths.add(entryName);
} else {
paths.add(entryName);
}
}
zip.close();
return paths;
}
/**
* Return the files' comment in ZIP file.
*
* @param zipFilePath The path of ZIP file.
* @return the files' comment in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getComments(final String zipFilePath)
throws IOException {
return getComments(getFileByPath(zipFilePath));
}
/**
* Return the files' comment in ZIP file.
*
* @param zipFile The ZIP file.
* @return the files' comment in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getComments(final File zipFile)
throws IOException {
if (zipFile == null) return null;
List<String> comments = new ArrayList<>();
ZipFile zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
comments.add(entry.getComment());
}
zip.close();
return comments;
}
private static boolean createOrExistsDir(final File file) {
return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
}
private static boolean createOrExistsFile(final File file) {
if (file == null) return false;
if (file.exists()) return file.isFile();
if (!createOrExistsDir(file.getParentFile())) return false;
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private static File getFileByPath(final String filePath) {
return isSpace(filePath) ? null : new File(filePath);
}
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
public static List<String> getFilesAllName(String path) {
File file=new File(path);
File[] files=file.listFiles();
if (files == null){Log.e("error","空目录");return null;}
List<String> s = new ArrayList<>();
for(int i =0;i<files.length;i++){
s.add(files[i].getAbsolutePath());
}
return s;
}
}
然后是分享文件到微信的工具类 ShareZipToWX.class:
(这里也有压缩方法,但是这个压缩文件的方法不是很好,因为他会拿到整个外部存储的文件路径,在解压缩文件是需要一个个打开文件到最底层,比较麻烦,而且因为Environment.getExternalStoragePublicDirectory(“”).getAbsolutePath() = /storage/emulated/0 这个方法是获取外部存储的根路径,这里有个 0,在电脑上是打不开的0.0)
package cnwy.xda.threedpolygontest.utils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 调用系统分享方法,把文件直接发送到微信
*/
public class ShareZipToWX {
public static final String PACKAGE_WECHAT = "com.tencent.mm";
/**
* 直接文件到微信好友
*
* @param picFile 文件路径
*/
public static void shareWechatFriend(Context mContext, File picFile) {
//首先判断是否安装微信
if (isInstallApp(mContext, ShareZipToWX.PACKAGE_WECHAT)) {
Intent intent = new Intent();
intent.setPackage("com.tencent.mm");
intent.setAction(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
String type = "*/*";
for (int i = 0; i < MATCH_ARRAY.length; i++) {
//判断文件的格式
if (picFile.getAbsolutePath().toString().contains(MATCH_ARRAY[i][0].toString())) {
type = MATCH_ARRAY[i][1];
break;
}
}
intent.setType(type);
Uri uri = null;
if (picFile != null) {
//这部分代码主要功能是判断了下文件是否存在,在android版本高过7.0(包括7.0版本)
//当前APP是不能直接向外部应用提供file开头的的文件路径,
//需要通过FileProvider转换一下。否则在7.0及以上版本手机将直接crash。
try {
ApplicationInfo applicationInfo = mContext.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(mContext,
mContext.getApplicationContext().getPackageName() + ".fileprovider", picFile);
} else {
uri = Uri.fromFile(picFile);
}
intent.putExtra(Intent.EXTRA_STREAM, uri);
} catch (Exception e) {
e.printStackTrace();
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if (getVersionCode(mContext, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
// }
mContext.startActivity(Intent.createChooser(intent, "分享文件"));
} else {
Toast.makeText(mContext, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
}
}
// 建立一个文件类型与文件后缀名的匹配表
private static final String[][] MATCH_ARRAY = {
//{后缀名, 文件类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".prop", "text/plain"},
{".rar", "application/x-rar-compressed"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
{"", "*/*"}
};
/**
* 压缩文件和文件夹
*
* @param srcFileString 要压缩的文件或文件夹
* @param zipFileString 压缩完成的Zip路径
* @throws Exception
*/
public static void ZipFolder(String srcFileString, String zipFileString) throws Exception {
//创建ZIP
ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
//创建文件
File file = new File(srcFileString);
//压缩
ZipFiles(file.getParent()+ File.separator, file.getName(), outZip);
//完成和关闭
outZip.finish();
outZip.close();
}
/**
* 压缩文件
*
* @param folderString
* @param fileString
* @param zipOutputSteam
* @throws Exception
*/
private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
if (zipOutputSteam == null)
return;
File file = new File(folderString + fileString);
if (file.isFile()) {
String path = folderString.replace(Environment.getExternalStoragePublicDirectory("/imagefiles").getPath()+"/","");
ZipEntry zipEntry = new ZipEntry(path+fileString);
FileInputStream inputStream = new FileInputStream(file);
zipOutputSteam.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[4096];
while ((len = inputStream.read(buffer)) != -1) {
zipOutputSteam.write(buffer, 0, len);
}
zipOutputSteam.closeEntry();
} else {
//文件夹
String fileList[] = file.list();
//没有子文件和压缩
if (fileList.length <= 0) {
ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
zipOutputSteam.putNextEntry(zipEntry);
zipOutputSteam.closeEntry();
}
//子文件和递归
for (int i = 0; i < fileList.length; i++) {
ZipFiles(folderString+fileString+"/", fileList[i], zipOutputSteam);
}
}
}
// 判断是否安装指定app
public static boolean isInstallApp(Context context, String app_package) {
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pInfo = packageManager.getInstalledPackages(0);
if (pInfo != null) {
for (int i = 0; i < pInfo.size(); i++) {
String pn = pInfo.get(i).packageName;
if (app_package.equals(pn)) {
return true;
}
}
}
return false;
}
/**
* 分享文件到微信好友 by WXAPI
*
* @param thumbId 分享到微信显示的图标
*/
// public static void shareFileToWechat(Context context, File file, int thumbId) {
// if (!isInstallApp(context, ShareUtils.PACKAGE_WECHAT)) {
// Toast.makeText(context, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
// return;
// }
// //ANDROID 11上微信分享得走FileProvider
// Log.d("share", "SDK_INT=" + Build.VERSION.SDK_INT);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
// shareWechatFriend(context, file);
// return;
// }
// //构建发送文件体
// WXFileObject fileObject = new WXFileObject();
// /*经实测,不给fileObject设置fileData,也是可以分享文件得,且大小默认10M以内
// 反而是设置了fileData属性的话,分享文件大小不能大于500kb,且在Android11以上无法分享,坑啊,
// 所以,在Android11上需要走FileProvider文件分享的方式*/
// //设置需要发送的文件byte[]
// //byte[] fileBytes = readFile(file);
// //fileObject.setFileData(fileBytes);
// fileObject.setFilePath(file.getAbsolutePath());
// fileObject.setContentLengthLimit(1024 * 1024 * 10);
// //使用媒体消息分享
// WXMediaMessage msg = new WXMediaMessage(fileObject);
// //这个title有讲究,最好设置为带后缀的文件名,否则可能分享到微信后无法读取
// msg.title = file.getName();
// //设置显示的预览图 需小于32KB
// if (thumbId <= 0) thumbId = R.mipmap.ic_launcher;
// msg.thumbData = readBitmap(context, thumbId);
// //发送请求
// SendMessageToWX.Req req = new SendMessageToWX.Req();
// //创建唯一标识
// req.transaction = String.valueOf(System.currentTimeMillis());
// req.message = msg;
// req.scene = SendMessageToWX.Req.WXSceneSession; //WXSceneSession:分享到对话
// // 通过WXAPIFactory工厂,获取IWXAPI的实例
// IWXAPI api = WXAPIFactory.createWXAPI(context, WXEntryActivity.APP_ID, true);
// // 将应用的appId注册到微信
// api.registerApp(WXEntryActivity.APP_ID);
// api.sendReq(req);
// }
/**
* 图片读取成byte[]
*/
private static byte[] readBitmap(Context context, int resourceId) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
return null;
}
/**
* file文件读取成byte[]
*/
private static byte[] readFile(File file) {
RandomAccessFile rf = null;
byte[] data = null;
try {
rf = new RandomAccessFile(file, "r");
data = new byte[(int) rf.length()];
rf.readFully(data);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
closeQuietly(rf);
}
return data;
}
//关闭读取file
private static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
在项目中应用:
//分享到微信
long createTime = TaskInfoAppDbUtils.getTasksByTaskId(appDb.getTaskId()).getCreateTime();
String zipPath= Environment.getExternalStoragePublicDirectory("/"+createTime+"-Out3DZip.zip").getPath();
Log.d("HandlerPopDialog","保存zip路径: " + zipPath);
// String filepath =mContext.getExternalCacheDir() + File.separator + "FiledataDir";
List<String> listfileinfo = ZipUtils.getFilesAllName(savePath);//savePath是文件路径,listfileinfo 是savePath下的所有文件名
Log.i("HandlerPopDialog", "handleMessage: 文件路径=" + listfileinfo);
new Thread(new Runnable() {
@Override
public void run() {
//直接使用ShareZipToWX中的压缩方法并分享
// try {
// ZipFolder(savePath,zipPath2);
// File fileZip = new File(zipPath2);
// shareWechatFriend(mContext,fileZip);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (Exception e) {
// e.printStackTrace();
// }
//使用ZipUtils中的压缩方法然后用ShareZipToWX的分享
try {
ZipUtils.zipFiles(listfileinfo,zipPath );/*filepath + File.separator + createTime+"-Out3DZip.zip"*/
File fileZip = new File(zipPath);
shareWechatFriend(mContext,fileZip);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
|