本文介绍如何复制设备目录到外接U盘目录
获取U盘目录
public static List<String> getUsbPaths(Context cxt) {
List<String> usbPaths = new ArrayList<>();
try {
StorageManager srgMgr = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE);
Class<StorageManager> srgMgrClass = StorageManager.class;
String[] paths = (String[]) srgMgrClass.getMethod("getVolumePaths").invoke(srgMgr);
for (String path : paths) {
Object volumeState = srgMgrClass.getMethod("getVolumeState", String.class).invoke(srgMgr, path);
if (!path.contains("emulated") && Environment.MEDIA_MOUNTED.equals(volumeState)) usbPaths.add(path);
}
} catch (Exception e) {
e.printStackTrace();
}
return usbPaths;
}
复制文件夹
public boolean copy(String fromFile, String toFile) {
File[] currentFiles;
File root = new File(fromFile);
if (!root.exists()) {
return false;
}
currentFiles = root.listFiles();
File targetDir = new File(toFile);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
for (int i = 0; i < currentFiles.length; i++) {
if (currentFiles[i].isDirectory())
{
copy(currentFiles[i].getPath() + "/", toFile+ "/" + currentFiles[i].getName() + "/");
} else
{
CopySdcardFile(currentFiles[i].getPath(), toFile + "/"+ currentFiles[i].getName());
}
}
return true;
}
public boolean CopySdcardFile(String fromFile, String toFile) {
try {
InputStream fosfrom = new FileInputStream(fromFile);
OutputStream fosto = new FileOutputStream(toFile);
byte bt[] = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c);
}
fosfrom.close();
fosto.close();
return true;
} catch (Exception ex) {
return false;
}
}
复制指定目录到U盘
public File getPath() {
List<String> pathList = getUsbPaths(MainActivity.this);
Log.i(TAG, "pathList = " + pathList.size());
if (pathList.size() > 0) {
for (String path : pathList) {
File usbFile = new File(path);
File[] fileList = usbFile.listFiles();
for (File file : fileList) {
if (file.getName().equals("test")) {
return file;
}
}
}
return null;
} else {
return null;
}
}
public void pullFile() {
File f = getPath();
if (f != null) {
new Thread(new Runnable() {
@Override
public void run() {
copy(getExternalFilesDir("") + "/test",f.getPath());
}
}).start();
} else {
}
}