답변:
파일을 복사하여 대상 경로에 저장하려면 아래 방법을 사용하십시오.
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();
}
}
API 19 이상에서는 Java 자동 자원 관리를 사용할 수 있습니다.
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.
또는 FileChannel 을 사용 하여 파일을 복사 할 수 있습니다 . 그것은 수 많은 파일을 복사 할 때 빠른 바이트 복사 방법보다. 파일이 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)에서 예외 로 인해 실패합니다 FileOutputStream outStream = new FileOutputStream(dst);. 내가 아는 텍스트에 따르면 파일이 존재하지 않으므로 파일을 확인하고 dst.mkdir();필요한 경우 전화 를 걸지만 여전히 도움이되지 않습니다. 나는 또한 확인을 시도 dst.canWrite();하고 돌아왔다 false. 이것이 문제의 원인 일 수 있습니까? 그리고 그렇습니다 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>.
try ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
onProgressUpdate있습니까? 그래서 ProgressBar에 표시 할 수 있습니까? 수용 된 솔루션에서 while 루프의 진행 상황을 계산할 수 있지만 여기서 수행 방법을 볼 수는 없습니다.
그것을위한 코 틀린 확장
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
contentResolver.openInputStream(uri).
이들은 나를 위해 잘 작동
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();
}
}
}
대답하기에는 너무 늦을 수 있지만 가장 편리한 방법은
FileUtils'에스
static void copyFile(File srcFile, File destFile)
예, 이것은 내가 한 일입니다
`
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;
}
`
Kotlin을 사용하면 훨씬 간단 해집니다.
File("originalFileDir", "originalFile.name")
.copyTo(File("newFileDir", "newFile.name"), true)
true또는 false대상 파일을 덮어 쓰기위한 것
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
복사하는 동안 오류가 발생하면 실제로 입력 / 출력 스트림을 닫는 솔루션이 있습니다. 이 솔루션은 스트림 닫기를 복사하고 처리하기 위해 Apache Commons IO IOUtils 방법을 사용합니다.
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);
}
}