How to make a copy of a file in android?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
In my app I want to save a copy of a certain file with a different name (which I get from user)
Do I really need to open the contents of the file and write it to another file?
What is the best way to do so?
java android
add a comment |
In my app I want to save a copy of a certain file with a different name (which I get from user)
Do I really need to open the contents of the file and write it to another file?
What is the best way to do so?
java android
Pre Java7, I think the answer is yes you do. stackoverflow.com/questions/106770/….
– Paul Grime
Feb 15 '12 at 12:07
java2s.com/Code/Java/File-Input-Output/MoveaFile.htm
– run
Feb 15 '12 at 12:07
check older post
– Deepak
Feb 15 '12 at 12:18
add a comment |
In my app I want to save a copy of a certain file with a different name (which I get from user)
Do I really need to open the contents of the file and write it to another file?
What is the best way to do so?
java android
In my app I want to save a copy of a certain file with a different name (which I get from user)
Do I really need to open the contents of the file and write it to another file?
What is the best way to do so?
java android
java android
edited Dec 31 '14 at 15:29
SBerg413
12.9k45082
12.9k45082
asked Feb 15 '12 at 11:59
A SA S
1,20951525
1,20951525
Pre Java7, I think the answer is yes you do. stackoverflow.com/questions/106770/….
– Paul Grime
Feb 15 '12 at 12:07
java2s.com/Code/Java/File-Input-Output/MoveaFile.htm
– run
Feb 15 '12 at 12:07
check older post
– Deepak
Feb 15 '12 at 12:18
add a comment |
Pre Java7, I think the answer is yes you do. stackoverflow.com/questions/106770/….
– Paul Grime
Feb 15 '12 at 12:07
java2s.com/Code/Java/File-Input-Output/MoveaFile.htm
– run
Feb 15 '12 at 12:07
check older post
– Deepak
Feb 15 '12 at 12:18
Pre Java7, I think the answer is yes you do. stackoverflow.com/questions/106770/….
– Paul Grime
Feb 15 '12 at 12:07
Pre Java7, I think the answer is yes you do. stackoverflow.com/questions/106770/….
– Paul Grime
Feb 15 '12 at 12:07
java2s.com/Code/Java/File-Input-Output/MoveaFile.htm
– run
Feb 15 '12 at 12:07
java2s.com/Code/Java/File-Input-Output/MoveaFile.htm
– run
Feb 15 '12 at 12:07
check older post
– Deepak
Feb 15 '12 at 12:18
check older post
– Deepak
Feb 15 '12 at 12:18
add a comment |
9 Answers
9
active
oldest
votes
To copy a file and save it to your destination path you can use the method below.
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();
}
}
On API 19+ you can use 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);
}
}
}
}
7
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
7
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
8
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them infinally
.
– Pang
Apr 18 '14 at 10:14
3
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
1
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
|
show 8 more comments
Alternatively, you can use FileChannel to copy a file. It might be faster than the byte copy method when copying a large file. You can't use it if your file is bigger than 2GB though.
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();
}
2
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
I tried your solution and it fails for me with the exceptionjava.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at theFileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and calldst.mkdir();
if needed, but it still doesn't help. I also tried to checkdst.canWrite();
and it returnedfalse
. May this is the source of the problem? And yes, I have<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.
– Mike B.
Jun 26 '15 at 19:00
1
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your trytry ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
Is there any way to make this solution publish its progress toonProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.
– George Bezerra
Feb 22 '17 at 13:39
|
show 1 more comment
These worked nice for me
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();
}
}
}
add a comment |
Kotlin extension for it
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened viacontentResolver.openInputStream(uri)
.
– AjahnCharles
Jan 18 at 7:06
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
add a comment |
It might be too late for an answer but the most convenient way is using
FileUtils
's
static void copyFile(File srcFile, File destFile)
e.g. this is what I did
`
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;
}
`
17
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
1
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
add a comment |
This is simple on Android O (API 26), As you see:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File origin, File dest) throws IOException {
Files.copy(origin.toPath(), dest.toPath());
}
add a comment |
Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of 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);
}
}
add a comment |
Much simpler now with Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newCopyFileName", "newFile.name"), true)
true
orfalse
is for overwriting the destination file
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
add a comment |
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();
}
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9292954%2fhow-to-make-a-copy-of-a-file-in-android%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
To copy a file and save it to your destination path you can use the method below.
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();
}
}
On API 19+ you can use 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);
}
}
}
}
7
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
7
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
8
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them infinally
.
– Pang
Apr 18 '14 at 10:14
3
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
1
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
|
show 8 more comments
To copy a file and save it to your destination path you can use the method below.
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();
}
}
On API 19+ you can use 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);
}
}
}
}
7
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
7
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
8
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them infinally
.
– Pang
Apr 18 '14 at 10:14
3
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
1
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
|
show 8 more comments
To copy a file and save it to your destination path you can use the method below.
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();
}
}
On API 19+ you can use 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);
}
}
}
}
To copy a file and save it to your destination path you can use the method below.
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();
}
}
On API 19+ you can use 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);
}
}
}
}
edited Aug 26 '17 at 20:51
Thomas Vos
4,51041852
4,51041852
answered Feb 15 '12 at 12:59
RakshiRakshi
5,41932145
5,41932145
7
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
7
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
8
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them infinally
.
– Pang
Apr 18 '14 at 10:14
3
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
1
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
|
show 8 more comments
7
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
7
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
8
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them infinally
.
– Pang
Apr 18 '14 at 10:14
3
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
1
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
7
7
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
– A S
Feb 16 '12 at 9:51
7
7
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
@mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
– ItsNotAboutTheName
Apr 15 '13 at 10:20
8
8
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them in
finally
.– Pang
Apr 18 '14 at 10:14
If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them in
finally
.– Pang
Apr 18 '14 at 10:14
3
3
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
– pozuelog
Feb 19 '16 at 11:55
1
1
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
@adamfisk java.nio.file is not yet in any version of the Android API.
– mhsmith
Mar 16 '17 at 20:33
|
show 8 more comments
Alternatively, you can use FileChannel to copy a file. It might be faster than the byte copy method when copying a large file. You can't use it if your file is bigger than 2GB though.
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();
}
2
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
I tried your solution and it fails for me with the exceptionjava.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at theFileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and calldst.mkdir();
if needed, but it still doesn't help. I also tried to checkdst.canWrite();
and it returnedfalse
. May this is the source of the problem? And yes, I have<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.
– Mike B.
Jun 26 '15 at 19:00
1
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your trytry ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
Is there any way to make this solution publish its progress toonProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.
– George Bezerra
Feb 22 '17 at 13:39
|
show 1 more comment
Alternatively, you can use FileChannel to copy a file. It might be faster than the byte copy method when copying a large file. You can't use it if your file is bigger than 2GB though.
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();
}
2
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
I tried your solution and it fails for me with the exceptionjava.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at theFileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and calldst.mkdir();
if needed, but it still doesn't help. I also tried to checkdst.canWrite();
and it returnedfalse
. May this is the source of the problem? And yes, I have<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.
– Mike B.
Jun 26 '15 at 19:00
1
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your trytry ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
Is there any way to make this solution publish its progress toonProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.
– George Bezerra
Feb 22 '17 at 13:39
|
show 1 more comment
Alternatively, you can use FileChannel to copy a file. It might be faster than the byte copy method when copying a large file. You can't use it if your file is bigger than 2GB though.
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();
}
Alternatively, you can use FileChannel to copy a file. It might be faster than the byte copy method when copying a large file. You can't use it if your file is bigger than 2GB though.
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();
}
edited Jun 4 '14 at 6:21
answered Jan 22 '14 at 15:22
NullNonameNullNoname
1,80611111
1,80611111
2
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
I tried your solution and it fails for me with the exceptionjava.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at theFileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and calldst.mkdir();
if needed, but it still doesn't help. I also tried to checkdst.canWrite();
and it returnedfalse
. May this is the source of the problem? And yes, I have<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.
– Mike B.
Jun 26 '15 at 19:00
1
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your trytry ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
Is there any way to make this solution publish its progress toonProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.
– George Bezerra
Feb 22 '17 at 13:39
|
show 1 more comment
2
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
I tried your solution and it fails for me with the exceptionjava.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at theFileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and calldst.mkdir();
if needed, but it still doesn't help. I also tried to checkdst.canWrite();
and it returnedfalse
. May this is the source of the problem? And yes, I have<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.
– Mike B.
Jun 26 '15 at 19:00
1
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your trytry ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
Is there any way to make this solution publish its progress toonProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.
– George Bezerra
Feb 22 '17 at 13:39
2
2
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer.
– Viktor Brešan
Nov 29 '14 at 5:42
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested.
– Viktor Brešan
Nov 29 '14 at 5:43
I tried your solution and it fails for me with the exception
java.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at the FileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and call dst.mkdir();
if needed, but it still doesn't help. I also tried to check dst.canWrite();
and it returned false
. May this is the source of the problem? And yes, I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.– Mike B.
Jun 26 '15 at 19:00
I tried your solution and it fails for me with the exception
java.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
at the FileOutputStream outStream = new FileOutputStream(dst);
step. According to the text I realize, that the file doesn't exist, so I check it and call dst.mkdir();
if needed, but it still doesn't help. I also tried to check dst.canWrite();
and it returned false
. May this is the source of the problem? And yes, I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.– Mike B.
Jun 26 '15 at 19:00
1
1
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your try
try ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
@ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your try
try ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
– AlbertMarkovski
Oct 5 '16 at 16:44
Is there any way to make this solution publish its progress to
onProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.– George Bezerra
Feb 22 '17 at 13:39
Is there any way to make this solution publish its progress to
onProgressUpdate
, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here.– George Bezerra
Feb 22 '17 at 13:39
|
show 1 more comment
These worked nice for me
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();
}
}
}
add a comment |
These worked nice for me
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();
}
}
}
add a comment |
These worked nice for me
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();
}
}
}
These worked nice for me
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();
}
}
}
answered Apr 16 '15 at 20:44
Bojan KsenemanBojan Kseneman
12.8k14251
12.8k14251
add a comment |
add a comment |
Kotlin extension for it
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened viacontentResolver.openInputStream(uri)
.
– AjahnCharles
Jan 18 at 7:06
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
add a comment |
Kotlin extension for it
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened viacontentResolver.openInputStream(uri)
.
– AjahnCharles
Jan 18 at 7:06
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
add a comment |
Kotlin extension for it
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
Kotlin extension for it
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
answered Sep 21 '17 at 12:39
Dima RostopiraDima Rostopira
4,0443556
4,0443556
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened viacontentResolver.openInputStream(uri)
.
– AjahnCharles
Jan 18 at 7:06
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
add a comment |
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened viacontentResolver.openInputStream(uri)
.
– AjahnCharles
Jan 18 at 7:06
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened via
contentResolver.openInputStream(uri)
.– AjahnCharles
Jan 18 at 7:06
This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened via
contentResolver.openInputStream(uri)
.– AjahnCharles
Jan 18 at 7:06
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
Kotlin is love, Kotlin is life!
– Dev Aggarwal
Jan 18 at 20:19
add a comment |
It might be too late for an answer but the most convenient way is using
FileUtils
's
static void copyFile(File srcFile, File destFile)
e.g. this is what I did
`
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;
}
`
17
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
1
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
add a comment |
It might be too late for an answer but the most convenient way is using
FileUtils
's
static void copyFile(File srcFile, File destFile)
e.g. this is what I did
`
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;
}
`
17
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
1
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
add a comment |
It might be too late for an answer but the most convenient way is using
FileUtils
's
static void copyFile(File srcFile, File destFile)
e.g. this is what I did
`
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;
}
`
It might be too late for an answer but the most convenient way is using
FileUtils
's
static void copyFile(File srcFile, File destFile)
e.g. this is what I did
`
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;
}
`
answered Jun 19 '15 at 23:37
stopBugsstopBugs
15627
15627
17
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
1
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
add a comment |
17
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
1
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
17
17
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
FileUtils does not exist natively in Android.
– The Berga
May 2 '16 at 8:30
1
1
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
But there's a library made by Apache that do this and more: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…
– Ale Muzzi
Dec 9 '16 at 15:21
add a comment |
This is simple on Android O (API 26), As you see:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File origin, File dest) throws IOException {
Files.copy(origin.toPath(), dest.toPath());
}
add a comment |
This is simple on Android O (API 26), As you see:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File origin, File dest) throws IOException {
Files.copy(origin.toPath(), dest.toPath());
}
add a comment |
This is simple on Android O (API 26), As you see:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File origin, File dest) throws IOException {
Files.copy(origin.toPath(), dest.toPath());
}
This is simple on Android O (API 26), As you see:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File origin, File dest) throws IOException {
Files.copy(origin.toPath(), dest.toPath());
}
edited Feb 25 '18 at 0:33
Suragch
217k128725797
217k128725797
answered Dec 16 '17 at 7:00
LeeLee
11116
11116
add a comment |
add a comment |
Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of 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);
}
}
add a comment |
Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of 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);
}
}
add a comment |
Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of 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);
}
}
Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of 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);
}
}
answered Dec 31 '14 at 15:26
SBerg413SBerg413
12.9k45082
12.9k45082
add a comment |
add a comment |
Much simpler now with Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newCopyFileName", "newFile.name"), true)
true
orfalse
is for overwriting the destination file
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
add a comment |
Much simpler now with Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newCopyFileName", "newFile.name"), true)
true
orfalse
is for overwriting the destination file
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
add a comment |
Much simpler now with Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newCopyFileName", "newFile.name"), true)
true
orfalse
is for overwriting the destination file
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
Much simpler now with Kotlin:
File("originalFileDir", "originalFile.name")
.copyTo(File("newCopyFileName", "newFile.name"), true)
true
orfalse
is for overwriting the destination file
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
answered Jan 13 at 20:24
BlundellBlundell
57.8k29165199
57.8k29165199
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
add a comment |
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
Not so simple if your File comes from a Gallery intent Uri.
– AjahnCharles
Jan 18 at 5:55
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
@AjahnCharles why? stackoverflow.com/a/13209522/413127
– Blundell
Jan 18 at 9:26
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet)
– AjahnCharles
Jan 18 at 9:46
add a comment |
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();
}
}
}
add a comment |
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();
}
}
}
add a comment |
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();
}
}
}
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();
}
}
}
edited Nov 19 '18 at 3:22
answered Nov 17 '18 at 6:35
TarasantanTarasantan
533
533
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9292954%2fhow-to-make-a-copy-of-a-file-in-android%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Pre Java7, I think the answer is yes you do. stackoverflow.com/questions/106770/….
– Paul Grime
Feb 15 '12 at 12:07
java2s.com/Code/Java/File-Input-Output/MoveaFile.htm
– run
Feb 15 '12 at 12:07
check older post
– Deepak
Feb 15 '12 at 12:18