我正在使用下面的代码将包含文件和文件夹及其子文件夹的数据复制到我的应用程序的数据目录,但我得到异常,告诉目标位置不存在但是FileOutputStream
方法应该根据 javadoc 为该方法创建目标文件夹:
Constructs a new FileOutputStream that writes to path. The file will be truncated if it exists, and created if it doesn't exist.
代码是:
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
File innerDir;
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
//getting exception here...
Log.e("mgh", e.getMessage());
}
}
对于任何文件夹,logcat 错误如下所示:
09-06 15:14:20.981: E/mgh(19262): /data/data/ir.example.sampleapplication/pzl/ui/css/main.css: open failed: ENOENT (No such file or directory)