以下是我用来复制包含 txt 文件的文件夹的代码。该文件夹位于我的应用程序的资产文件夹中。当我复制时,我在out = new FileOutputStream(newFileName); 行中得到 File not found 异常;
当我将它保存到 /data/data 文件夹时,我可以完美地工作;IE; 内部存储器。我检查了 SD 卡的状态,它显示已安装。
public class CpyAsset extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
copyFileOrDir("edu1");//directory name in assets
}
File sdCard = Environment.getExternalStorageDirectory();
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
File dir = new File (sdCard.getAbsolutePath());
if (!dir.exists()){
System.out.println("Created directory"+sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation"+result);
}
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("Exception in copyFileOrDir"+ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = sdCard.getAbsolutePath() + "/"+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) {
System.out.println("Exception in copyFile"+e);
}
}
}
例外
01-01 06:13:34.783: INFO/System.out(11334): Exception in copyFilejava.io.FileNotFoundException: /mnt/sdcard/edu1/anees.txt: open failed: ENOENT (No such file or directory)
我尝试复制的文件夹(和内容)在 assets/edu1/abc.txt
有人可以让我知道是什么原因造成的,因为我找不到任何明显的原因吗?任何帮助深表感谢。