我目前正在尝试从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上得到一个null异常,这意味着目标文件包含...没有文件?是因为我无法从目标目录中读取?
有人可以开导我吗?
顺便说一下:
求助!
答案 0 :(得分:0)
试试这个,我为我工作,
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();
}