Di aplikasi saya, saya ingin menyimpan salinan file tertentu dengan nama yang berbeda (yang saya dapatkan dari pengguna)
Apakah saya benar-benar perlu membuka konten file dan menulisnya ke file lain?
Apa cara terbaik untuk melakukannya?
Di aplikasi saya, saya ingin menyimpan salinan file tertentu dengan nama yang berbeda (yang saya dapatkan dari pengguna)
Apakah saya benar-benar perlu membuka konten file dan menulisnya ke file lain?
Apa cara terbaik untuk melakukannya?
Jawaban:
Untuk menyalin file dan menyimpannya ke jalur tujuan Anda, Anda dapat menggunakan metode di bawah ini.
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
Pada API 19+ Anda dapat menggunakan Java Automatic Resource Management:
public static void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
finally.
Atau, Anda dapat menggunakan FileChannel untuk menyalin file. Ini mungkin lebih cepat daripada metode copy byte saat menyalin file besar. Anda tidak dapat menggunakannya jika file Anda lebih besar dari 2GB.
public void copy(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
java.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)di FileOutputStream outStream = new FileOutputStream(dst);langkah. Menurut teks yang saya sadari, bahwa file itu tidak ada, jadi saya memeriksanya dan menelepon dst.mkdir();jika perlu, tetapi masih tidak membantu. Saya juga mencoba memeriksa dst.canWrite();dan mengembalikannya false. Bisakah ini sumber masalahnya? Dan ya, sudah <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>.
try ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
onProgressUpdate, sehingga saya bisa menunjukkannya di ProgressBar? Dalam solusi yang diterima saya dapat menghitung kemajuan dalam loop sementara, tetapi saya tidak bisa melihat bagaimana melakukannya di sini.
Ekstensi Kotlin untuk itu
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
contentResolver.openInputStream(uri).
Ini bekerja baik untuk saya
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
Mungkin sudah terlambat untuk jawaban tetapi cara yang paling nyaman adalah menggunakan
FileUtilsini
static void copyFile(File srcFile, File destFile)
misalnya ini yang saya lakukan
`
private String copy(String original, int copyNumber){
String copy_path = path + "_copy" + copyNumber;
try {
FileUtils.copyFile(new File(path), new File(copy_path));
return copy_path;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
`
Lebih sederhana sekarang dengan Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newFileDir", "newFile.name"), true)
trueatau falseuntuk menimpa file tujuan
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
Berikut ini adalah solusi yang benar-benar menutup aliran input / output jika terjadi kesalahan saat menyalin. Solusi ini menggunakan metode apache Commons IO IOUtils untuk menyalin dan menangani penutupan aliran.
public void copyFile(File src, File dst) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dst);
IOUtils.copy(in, out);
} catch (IOException ioe) {
Log.e(LOGTAG, "IOException occurred.", ioe);
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
}