【发布时间】:2015-02-06 03:53:28
【问题描述】:
我想将文件从一个文件夹复制到另一个文件夹(例如: sdcard0/folder1/a.text 到 sdcard0/folder2 )。我在这个站点和其他站点中看到了很多示例代码,但没有一个对我有用。我不知道我的问题在哪里。我还向清单文件添加了权限。 我该怎么办? 为此我有几种方法,我将它们从 copy1 命名为 copy3 。
//----------Method 1
public void copy1(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
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);
}
in.close();
out.close();
}
//----------Method 2
public void copy2(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();
}
//----------Method 3
public static boolean copy3(File source, File dest){
try{
// Declaration et ouverture des flux
java.io.FileInputStream sourceFile = new java.io.FileInputStream(source);
try{
java.io.FileOutputStream destinationFile = null;
try{
destinationFile = new FileOutputStream(dest);
// Lecture par segment de 0.5Mo
byte buffer[] = new byte[512 * 1024];
int nbLecture;
while ((nbLecture = sourceFile.read(buffer)) != -1){
destinationFile.write(buffer, 0, nbLecture);
}
} finally {
destinationFile.close();
}
} finally {
sourceFile.close();
}
} catch (IOException e){
e.printStackTrace();
return false; // Erreur
}
return true; // Résultat OK
}
我像这样使用它们: 字符串路径=Environment.getExternalStorageDirectory().toString(); 文件 f= 新文件(路径 +"/folder1/a.txt"); 文件 f2= 新文件(路径+"/folder2/" ); 尝试{ 复制1(f,f2); } 捕获(异常 e){}
也用于创建目录:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/AAAli");
if(!dir.exists()) {
dir.mkdirs(); // build directory
}
【问题讨论】:
-
显示您尝试过的代码
-
帮帮我。我该怎么办?
标签: android file directory copy-paste