No meu aplicativo, quero salvar uma cópia de um determinado arquivo com um nome diferente (que recebo do usuário)
Eu realmente preciso abrir o conteúdo do arquivo e gravá-lo em outro arquivo?
Qual é a melhor forma de fazê-lo?
No meu aplicativo, quero salvar uma cópia de um determinado arquivo com um nome diferente (que recebo do usuário)
Eu realmente preciso abrir o conteúdo do arquivo e gravá-lo em outro arquivo?
Qual é a melhor forma de fazê-lo?
Respostas:
Para copiar um arquivo e salvá-lo no caminho de destino, você pode usar o método abaixo.
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();
}
}
Na API 19+, você pode usar o 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.
Como alternativa, você pode usar o FileChannel para copiar um arquivo. Ele pode ser mais rápido do que o método de cópia byte ao copiar um arquivo grande. Você não pode usá-lo se o seu arquivo tiver mais de 2 GB.
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)na FileOutputStream outStream = new FileOutputStream(dst);etapa. De acordo com o texto, percebo que o arquivo não existe, então verifico e ligo dst.mkdir();se necessário, mas ainda não ajuda. Eu também tentei verificar dst.canWrite();e ele retornou false. Esta é a fonte do problema? E sim, eu tenho <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>.
try ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
onProgressUpdateque eu possa mostrá-la em uma ProgressBar? Na solução aceita, posso calcular o progresso no loop while, mas não consigo ver como fazê-lo aqui.
Extensão Kotlin para ele
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
contentResolver.openInputStream(uri).
Eles funcionaram bem para mim
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();
}
}
}
Pode ser tarde demais para uma resposta, mas a maneira mais conveniente é usar
FileUtilsé
static void copyFile(File srcFile, File destFile)
por exemplo, foi o que eu fiz
`
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;
}
`
Muito mais simples agora com Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newFileDir", "newFile.name"), true)
trueou falseé para substituir o arquivo de destino
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
Aqui está uma solução que realmente fecha os fluxos de entrada / saída se ocorrer um erro durante a cópia. Esta solução utiliza os métodos apache Commons IO IOUtils para copiar e manipular o fechamento de fluxos.
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);
}
}