我想将apk中的文本文档推送到/ system目录(是的,它是root用户的应用程序),并想知道我将如何做到这一点:)我的txt文件在assests文件夹中,但它可能是如果需要使用
答案 0 :(得分:3)
将文本文件放在项目的assets目录中,然后使用以下线程中的代码将其解压缩到文件系统: How to copy files from 'assets' folder to sdcard?
编辑:这是我使用的一些代码。对于sourceFileName,传递相对于assets文件夹的assets文件的名称(例如,如果您在assets文件夹中有myFile.txt,则传递myFile.txt)。对于目标文件,传递完整路径(例如/data/data/com.mycompany/mypackage/myFile.txt)。 context是当前活动(例如MyActivity.this)。
private boolean copyFile(Context context, String sourceFileName, String destFileName)
{
AssetManager assetManager = context.getAssets();
File destFile = new File(destFileName);
File destParentDir = destFile.getParentFile();
destParentDir.mkdir();
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(sourceFileName);
out = new FileOutputStream(destFile);
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;
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
EDIT2:原来/ system分区以只读方式挂载,即使在root设备上也是如此。这可能有所帮助:Android: how to mount filesystem in RW from within my APK? (rooted, of course)
答案 1 :(得分:0)
您可以尝试此功能(找到here):
public String runSystemCommand(String cmd)
{
try {
// Executes the command.
Process process = Runtime.getRuntime().exec(cmd);
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
我自己也是这样尝试的:
String cmdoutput = this.runSystemCommand("/system/bin/ls .");
Log.d("SampleAndroidInterfaceActivity", "runSystemCommand() returned: " + cmdoutput);
并且运作良好。这是我的输出:
05-16 17:50:10.423: runSystemCommand() returned: acct
05-16 17:50:10.423: cache
05-16 17:50:10.423: config
05-16 17:50:10.423: d
05-16 17:50:10.423: data
05-16 17:50:10.423: default.prop
05-16 17:50:10.423: dev
05-16 17:50:10.423: etc
05-16 17:50:10.423: init
05-16 17:50:10.423: init.goldfish.rc
05-16 17:50:10.423: init.rc
05-16 17:50:10.423: mnt
05-16 17:50:10.423: proc
05-16 17:50:10.423: root
05-16 17:50:10.423: sbin
05-16 17:50:10.423: sdcard
05-16 17:50:10.423: sys
05-16 17:50:10.423: system
05-16 17:50:10.423: ueventd.goldfish.rc
05-16 17:50:10.423: ueventd.rc
05-16 17:50:10.423: vendor
如果您知道txt文件的绝对路径,则可以使用cp
轻松复制它。