如何以编程方式在SD上移动,复制和删除文件和目录?

Ton*_*ony 84 directory android copy file move

我想以编程方式移动,复制和删除SD卡上的文件和目录.我已经完成了谷歌搜索,但找不到任何有用的东西.

Dan*_*ahy 150

在清单中设置正确的权限

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

下面是一个以编程方式移动文件的函数

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());
    }

}
Run Code Online (Sandbox Code Playgroud)

删除文件使用

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

复印

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());
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记在清单中设置权限<uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE"/> (8认同)
  • 另外,不要忘记在inputPath和outputPath的末尾添加斜杠,例如:/ sdcard/NOT/sdcard (4认同)
  • 另外,不要忘记通过 AsyncTask 或 Handler 等在后台线程上执行这些。 (3认同)

Won*_*res 133

移动文件:

File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);
Run Code Online (Sandbox Code Playgroud)

  • 抬头; "两条路径都在同一个挂载点上.在Android上,当尝试在内部存储和SD卡之间进行复制时,应用程序最有可能达到此限制." (31认同)

asi*_*ura 36

移动文件的功能:

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

  • @BlueMango 删除第 10 行 `file.delete()` (3认同)

Com*_*are 24

使用标准的Java I/O.用于Environment.getExternalStorageDirectory()访问外部存储的根目录(在某些设备上是SD卡).

  • 实际上,标准Java I/O java.nio.file中最相关的部分很遗憾在Android(API级别21)上不可用. (9认同)
  • 随着 android 10 范围存储的发布成为新规范,所有对文件进行操作的方法也发生了变化,java.io 的操作方式将不再起作用,除非您在清单中添加值为“true”的“RequestLagacyStorage”方法 Environment.getExternalStorageDirectory() 也被废弃 (4认同)

dug*_*ggu 16

删除

public static void deleteRecursive(File fileOrDirectory) {

 if (fileOrDirectory.isDirectory())
    for (File child : fileOrDirectory.listFiles())
        deleteRecursive(child);

    fileOrDirectory.delete();

    }
Run Code Online (Sandbox Code Playgroud)

检查链接以获取上述功能.

复制

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();
}

}
Run Code Online (Sandbox Code Playgroud)

移动

移动只是将文件夹的一个位置复制到另一个位置然后删除的文件夹

表现

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)


Ken*_*Ken 10

  1. 权限:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    Run Code Online (Sandbox Code Playgroud)
  2. 获取SD卡根文件夹:

    Environment.getExternalStorageDirectory()
    
    Run Code Online (Sandbox Code Playgroud)
  3. 删除文件:这是关于如何删除根文件夹中所有空文件夹的示例:

    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);
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 拷贝文件:

    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();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 移动文件=复制+删除源文件


xna*_*gyg 6

File from = new File(Environment.getExternalStorageDirectory().getAbsolutePath().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);
Run Code Online (Sandbox Code Playgroud)

  • [File.renameTo](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File))仅适用于同一文件系统卷.你也应该检查renameTo的结果. (6认同)

Ahm*_*met 6

在 Kotlin 中你可以使用 copyTo() 扩展函数,

sourceFile.copyTo(destFile, true)
Run Code Online (Sandbox Code Playgroud)


Let*_*ock 5

使用Square的Okio复制文件:

BufferedSink bufferedSink = Okio.buffer(Okio.sink(destinationFile));
bufferedSink.writeAll(Okio.source(sourceFile));
bufferedSink.close();
Run Code Online (Sandbox Code Playgroud)