0

以下是我用来复制包含 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

有人可以让我知道是什么原因造成的,因为我找不到任何明显的原因吗?任何帮助深表感谢。

4

3 回答 3

2

您总是试图在这部分创建外部存储根目录:

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);
}

所以您没有创建文件夹edu1/,并且在该文件夹中创建anees.txt文件将失败。

于 2012-06-19T13:44:54.890 回答
1

试试这个方法......

File f = new File("/sdcard/assets/edu1/abc.txt");

FileWriter fw = new FileWriter(f);

BufferedWriter bw = new BufferedWriter(fw);
于 2012-06-19T13:26:41.930 回答
1

在您的代码中,您检查 sdcard 路径是否存在,而您应该检查导致目录“edu1”从未创建的路径尝试改用它

File dir = new File (sdCard.getAbsolutePath()+"/"+path);
于 2012-06-19T13:35:25.097 回答