Android:从根应用程序文件夹读取内容。
问题描述:
我目前正在尝试从android应用程序的根目录读取内容。我实现所有的权限在我的表现为如下陈述:Android:从根应用程序文件夹读取内容。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
和我的代码:
public void copytoFileDestination(){
//get the root path of the application.
String rootPath = getFilesDir().getPath() + "/images/";
File destination = new File(rootPath);
String imgPath = "/storage/emulated/0/Pictures/somefilename.jpg"
File source = new File(imgPath);
try{
//copy source location to destination directory
copyFile(source, destination);
//display all the contents of rootPath! How? Attempt:
File[] files = destination.listFiles();
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
Log.d("copy file", "complete");
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
我从源(图像路径)只是想复制到目的地(根路径)然后显示目的地的内容。然而,我在files.length得到一个空的异常,这意味着目标文件包含...没有文件?是因为我无法从目标目录读取吗?
有人能够启发我吗?
顺便说一句:
- destination.exist()是正确的。
- destination.canRead()为true。
帮忙!
答
试试这个,我对我的作品,
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
byte[] var1 = new byte[1024];
int var2;
while((var2 = source.read(var1)) > 0) {
destination.write(var1, 0, var2);
}
source.close();
destination.close();
}