Android 从任何地方复制和重命名
Android Copy and Rename from anywhere
尝试使用以下代码将文件从一个目录复制到另一个目录并重命名
String Path3= "/storage/extSDCard/DCIM/Camera/fred.jpg";
File to = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Barr.jpg");
File oldFile = new File (Path3);
oldFile.renameTo(to);
似乎没有复制文件。在这种情况下,路径 Path3 在 SDCard 上,但我也需要它从设备上的一个目录复制到另一个目录
基本上我使用图库选择器从某处选择图像我将 uri 转换为路径然后我需要将文件从存储它的位置复制到图片目录并重命名它
知道我哪里出错了吗?
我从各种渠道解决了这个问题,但解决方法不对。此代码有效:
File sourceLocation = new File (Path2);
File targetLocation = new File (Path3 + "/" + imageFileName);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
int actionChoice = 2;
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
else{
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
尝试使用以下代码将文件从一个目录复制到另一个目录并重命名
String Path3= "/storage/extSDCard/DCIM/Camera/fred.jpg";
File to = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Barr.jpg");
File oldFile = new File (Path3);
oldFile.renameTo(to);
似乎没有复制文件。在这种情况下,路径 Path3 在 SDCard 上,但我也需要它从设备上的一个目录复制到另一个目录
基本上我使用图库选择器从某处选择图像我将 uri 转换为路径然后我需要将文件从存储它的位置复制到图片目录并重命名它
知道我哪里出错了吗?
我从各种渠道解决了这个问题,但解决方法不对。此代码有效:
File sourceLocation = new File (Path2);
File targetLocation = new File (Path3 + "/" + imageFileName);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
int actionChoice = 2;
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
else{
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}