这里是关于如何打包和运行可执行文件的完整指南。我基于我在这里找到的内容和其他链接,以及我自己的反复试验。
1.) 在您的 SDK 项目中,将可执行文件放在您的 /assets 文件夹中
2.) 像这样以编程方式获取该文件目录 (/data/data/your_app_name/files) 的字符串
String appFileDirectory = getFilesDir().getPath();
String executableFilePath = appFileDirectory + "/executable_file";
3.) 在应用程序的项目 Java 代码中:将可执行文件从 /assets 文件夹复制到应用程序的“文件”子文件夹(通常是 /data/data/your_app_name/files),函数如下:
private void copyAssets(String filename) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
Log.d(TAG, "Attempting to copy this file: " + filename); // + " to: " + assetCopyDestination);
try {
in = assetManager.open(filename);
Log.d(TAG, "outDir: " + appFileDirectory);
File outFile = new File(appFileDirectory, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e(TAG, "Failed to copy asset file: " + filename, e);
}
Log.d(TAG, "Copy success: " + filename);
}
4.) 更改 executable_file 上的文件权限以使其真正可执行。使用 Java 调用来实现:
File execFile = new File(executableFilePath);
execFile.setExecutable(true);
5.) 像这样执行文件:
Process process = Runtime.getRuntime().exec(executableFilePath);
请注意,此处引用的任何文件(例如输入和输出文件)都必须构造完整的路径字符串。这是因为这是一个独立的衍生进程,它不知道“pwd”是什么。
如果你想读取命令的标准输出,你可以这样做,但到目前为止,它只适用于系统命令(如“ls”),而不是可执行文件:
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();
process.waitFor();
Log.d(TAG, "输出:" + output.toString());