首页 > 解决方案 > 将文件写入模拟器中的 /system/app 文件夹

问题描述

我正在尝试在 Android Emulator 中将 apk 写入 /system/app 位置。这是我的代码:

File path = Environment.getRootDirectory();
File fileToWrite = new File(path, "/" + fileName);

byte[] buff = new byte[1024];
int l = 0;
// write buffer to file
FileOutputStream fos = new FileOutputStream(fileToWrite);
while((l = zis.read(buff)) > 0){
    fos.write(buff,0, l);
}
fos.close();

我的 AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

但是,我收到以下错误消息:

java.io.FileNotFoundException: /system/MainApp-debug.apk (只读文件系统) 06-08 08:51:59.858 2921-3160/com.mainapp W/System.err: at java.io.FileOutputStream.open0 (本机方法)在 java.io.FileOutputStream.open(FileOutputStream.java:287)

/mnt/sdcard/Download我设法使用相同的代码写入文件夹。但我不确定为什么它无法写入/system/app文件夹。

有任何想法吗?谢谢!

标签: javaandroidemulation

解决方案


这是我用于创建路径的代码:

    public static File root = android.os.Environment
        .getExternalStorageDirectory();

public static String path = root.getAbsolutePath() + "/" + directoryName
        + "/";

public static boolean CreateDirectory() {

    boolean ret = false;
    path = root.getAbsolutePath() + "/" + directoryName + "/";
    File folderExisting = new File(root.getAbsolutePath(), directoryName);

    if (folderExisting.exists()) {
        ret = true;
    } else {
        ret = folderExisting.mkdir();
        // ret = false;
    }

    return ret;
}

然后保存东西:

    public static boolean SaveToSD(List<String> data, String fileName) {

    // File root = android.os.Environment.getExternalStorageDirectory();
    boolean ret = false;
    CreateDirectory();
    File file = new File(path, fileName);

    try {
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        for (int idx = 0; idx < data.size(); idx++) {
            if (data.get(idx) != null)
                pw.println(data.get(idx));
        }

        pw.flush();
        pw.close();
        f.close();
        ret = true;
    } catch (FileNotFoundException e) {
        ret = false;
        e.printStackTrace();
    } catch (IOException e) {
        ret = false;
        e.printStackTrace();
    }

    return ret;

}

希望对你有帮助

对于一个对象:

        FileOutputStream fos = new FileOutputStream("file");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(mb);
        oos.close();

推荐阅读