20

SDカードに存在するフォルダを、プログラムで同じSDカードを提示する別のフォルダにコピーすることは可能ですか??

もしそうなら、それを行う方法は?

4

5 に答える 5

43

その例の改良版:

// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists() && !targetLocation.mkdirs()) {
            throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
        }

        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        // make sure the directory we plan to store the recording in exists
        File directory = targetLocation.getParentFile();
        if (directory != null && !directory.exists() && !directory.mkdirs()) {
            throw new IOException("Cannot create dir " + directory.getAbsolutePath());
        }

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

渡されたターゲット ファイルが存在しないディレクトリにある場合のエラー処理と処理が改善されました。

于 2012-06-21T10:00:48.673 に答える
14

ここの例を参照してください。SDカードは外部ストレージなので、経由でアクセスできますgetExternalStorageDirectory

于 2011-04-19T11:00:27.040 に答える
5

はい、それは可能であり、私のコードで以下のメソッドを使用しています。あなたに完全に使用することを願っています:-

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

}
于 2013-02-07T10:28:38.850 に答える
1

ファイルまたはディレクトリを移動するには、File.renameTo(String path)関数を使用できます

File oldFile = new File (oldFilePath);
oldFile.renameTo(newFilePath);
于 2013-05-20T00:47:54.200 に答える