java - 如何使用 File.move()
问题描述
我想将文件从下载文件夹移动到我的应用程序中的文件夹,我看到您可以使用 Files.move (source, destination) 功能,但我不知道如何获取源和目标路径.
当你尝试
String sdCard = Environment.getExternalStorageDirectory().toString();
File ficheroPrueba = new File(sdCard + "/pau_alem18je_compressed.pdf");
if(ficheroPrueba.exists())
Log.v(TAG, "Hola")
}
尽管已经下载了文件(在 android 模拟器的下载中可以看到),但它不会打印 log.v
解决方案
使用 Environment.getExternalStorageDirectory() 获取外部存储的根目录(在某些设备上,它是 SD 卡)。
String sdCard = Environment.getExternalStorageDirectory().toString();
// the file to be moved or copied
File sourceLocation = new File (sdCard + "/sample.txt");
// make sure your target location folder exists!
File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");
// just to take note of the location sources
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else{
// make sure the target file exists
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
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();
}
}
推荐阅读
- java - 没有设置器的“Beans”的 JavaBeanBooleanPropertyBuilder
- vb.net - 如何添加多个文本框的值并在另一个 TextBoChanged 属性中显示
- formal-languages - 使用泵引理证明语言不是上下文无关的
- timer - 计数器错误中的异步加载数据
- linux - 从本地复制的 repo 安装 pip
- python - 试图伪造和轮换用户代理
- flutter - Flutter - 如何在网络未连接时确定使用 Firestore
- angular - 如何从集合中获取一个文档,离子选择列出所有文档?
- audio - 使用 Julia 在声音上使用 fft
- java - 为什么我缓冲的 `String` 与 `RegEx` 模式不匹配?