In meiner App möchte ich eine Kopie einer bestimmten Datei mit einem anderen Namen speichern (den ich vom Benutzer bekomme).
Muss ich den Inhalt der Datei wirklich öffnen und in eine andere Datei schreiben?
Was ist der beste Weg, dies zu tun?
Um eine Datei zu kopieren und im Zielpfad zu speichern, können Sie die folgende Methode verwenden.
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();
}
}
Auf API 19+ können Sie Java Automatic Resource Management verwenden:
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);
}
}
}
}
Alternativ können Sie auch FileChannel verwenden, um eine Datei zu kopieren. Könnte schneller sein als die Byte-Kopiermethode beim Kopieren einer großen Datei. Sie können es nicht verwenden, wenn Ihre Datei größer als 2 GB ist.
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();
}
Diese haben für mich gut funktioniert
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();
}
}
}
Kotlin-Erweiterung dafür
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
Für eine Antwort ist es vielleicht zu spät, aber der bequemste Weg ist die Verwendung
FileUtils
's
static void copyFile(File srcFile, File destFile)
z.B. das habe ich getan
`
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;
}
`
Dies ist auf Android O (API 26) einfach. Wie Sie sehen:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File Origin, File dest) throws IOException {
Files.copy(Origin.toPath(), dest.toPath());
}
Hier ist eine Lösung, die die Eingabe-/Ausgabeströme tatsächlich schließt, wenn beim Kopieren ein Fehler auftritt. Diese Lösung verwendet die IOUtils-Methoden von Apache Commons IO zum Kopieren und Verwalten des Schließens von Streams.
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);
}
}
Mit Kotlin jetzt viel einfacher:
File("originalFileDir", "originalFile.name")
.copyTo(File("newCopyFileName", "newFile.name"), true)
true
orfalse
dient zum Überschreiben der Zieldatei
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/Java.io.-file/copy-to.html
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis = new FileInputStream(from);
fos=new FileOutputStream(to);
byte[] by=new byte[fis.available()];
int len;
while((len=fis.read(by))>0){
fos.write(by,0,len);
}
}catch (Throwable t){
Toast.makeText(context,t.toString(),Toast.LENGTH_LONG).show();
}
finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
}
}
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
}
}
}