Como mover, copiar e apagar os ficheiros e directórios do SD de forma programática?
quero mover programaticamente, copiar e apagar ficheiros e directórios no cartão SD. Fiz uma pesquisa no Google, mas não encontrei nada útil.
13 answers
Usar a norma Java I / o . Use Environment.getExternalStorageDirectory()
para chegar à raiz do armazenamento externo (que, em alguns dispositivos, é um cartão SD).
Define as permissões correctas no manifesto
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Abaixo está uma função que irá programaticamente mover o seu ficheiro
private void moveFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file
out.flush();
out.close();
out = null;
// delete the original file
new File(inputPath + inputFile).delete();
}
catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
Para Apagar o ficheiro use
private void deleteFile(String inputPath, String inputFile) {
try {
// delete the original file
new File(inputPath + inputFile).delete();
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
To copy
private void copyFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file (You have now copied the file)
out.flush();
out.close();
out = null;
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
Mover o ficheiro:
File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);
Função para mover ficheiros:
private void moveFile(File file, File dir) throws IOException {
File newFile = new File(dir, file.getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
file.delete();
} finally {
if (inputChannel != null) inputChannel.close();
if (outputChannel != null) outputChannel.close();
}
}
Apagar
public static void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
Verifique esta ligação para a função acima.
Copiar
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
Mover
Mover não é nada apenas copiar a pasta de um local para outro depois apagar a pasta é isso
Manifesto
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
Permissões:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
Obter a pasta raiz do cartão SD:
Environment.getExternalStorageDirectory()
-
Apagar o ficheiro: Este é um exemplo de como apagar todas as pastas vazias numa pasta de raiz:
public static void deleteEmptyFolder(File rootFolder){ if (!rootFolder.isDirectory()) return; File[] childFiles = rootFolder.listFiles(); if (childFiles==null) return; if (childFiles.length == 0){ rootFolder.delete(); } else { for (File childFile : childFiles){ deleteEmptyFolder(childFile); } } }
-
Copiar o ficheiro:
public static void copyFile(File src, File dst) throws IOException { FileInputStream var2 = new FileInputStream(src); FileOutputStream var3 = new FileOutputStream(dst); byte[] var4 = new byte[1024]; int var5; while((var5 = var2.read(var4)) > 0) { var3.write(var4, 0, var5); } var2.close(); var3.close(); }
Mover o ficheiro = copiar + apagar o ficheiro de código
File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);
Copiar o ficheiro com o quadrado Okio:
BufferedSink bufferedSink = Okio.buffer(Okio.sink(destinationFile));
bufferedSink.writeAll(Okio.source(sourceFile));
bufferedSink.close();
Se está a usar goiaba, pode usar os ficheiros .mover(origem, dest)
/**
* Copy the local DB file of an application to the root of external storage directory
* @param context the Context of application
* @param dbName The name of the DB
*/
private void copyDbToExternalStorage(Context context , String dbName){
try {
File name = context.getDatabasePath(dbName);
File sdcardFile = new File(Environment.getExternalStorageDirectory() , "test.db");//The name of output file
sdcardFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
inputStream = new FileInputStream(name);
outputStream = new FileOutputStream(sdcardFile);
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception e) {
Log.e("Exception" , e.toString());
}
}
Andróide Xamarin
public static bool MoveFile(string CurrentFilePath, string NewFilePath)
{
try
{
using (var f = new File(CurrentFilePath))
using (var i = new FileInputStream(f))
using (var o = new FileOutputStream(NewFilePath))
{
i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
f.Delete();
}
return true;
}
catch { return false; }
}
public static bool CopyFile(string CurrentFilePath, string NewFilePath)
{
try
{
using (var i = new FileInputStream(CurrentFilePath))
using (var o = new FileOutputStream(NewFilePath))
i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
return true;
}
catch { return false; }
}
public static bool DeleteFile(string FilePath)
{
try
{
using (var file = new File(FilePath))
file.Delete();
return true;
}
catch { return false; }
}
Para mover um ficheiro esta api pode ser usada, mas você precisa do atleat 26 Como nível de api -
Mas se quiser mover a pasta, não existe suporte para que este código nativo possa ser usado
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import java.io.File;
public class FileModule {
public void moveDirectory(String src, String des) {
File srcDir = new File(src);
File destDir = new File(des);
try {
FileUtils.moveDirectory(srcDir,destDir);
} catch (Exception e) {
Log.e("Exception" , e.toString());
}
}
public void deleteDirectory(String dir) {
File delDir = new File(dir);
try {
FileUtils.deleteDirectory(delDir);
} catch (IOException e) {
Log.e("Exception" , e.toString());
}
}
}
uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
Código:
final Class<?> surfaceControlClass = Class.forName("android.os.storage.StorageManager");
Method method1 = surfaceControlClass.getMethod("getVolumePaths")
method1.setAccessible(true);
final Object object = context.getSystemService(Context.STORAGE_SERVICE);
String[] volumes = method1.invoke(object)