gpt4 book ai didi

java - Android getfilesdir() 中的空指针

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:54 26 4
gpt4 key购买 nike

我在 getfilesdir() 上收到 NULL 指针消息。我确信这与我的实现有关,但我不太确定它是什么。我对 Android 开发非常陌生。

    public class MainActivity extends AppCompatActivity {

String appFileDirectory = getFilesDir().getPath();
String executableFilePath = appFileDirectory + "/iperf3";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyFile("iperf3");
}

private static final String TAG = "MainActivity";

//This function is used to copy the iperf3 executable to a directory which execute permissions for this application, and then gives it execute permissions.
//It runs on every initiation of an iperf3 test, but copies the file only if it's needed.
public void copyFile(String filename) {
AssetManager assetManager = getAssets();
try {
InputStream in = assetManager.open(filename);
File outFile = new File(appFileDirectory, filename);
OutputStream out = new FileOutputStream(outFile);

Log.d(TAG, "Attempting to copy this file: " + filename); // + " to: " + assetCopyDestination);

int read;
byte[] buffer = new byte[4096];
while ((read = in.read(buffer)) > 0) {
out.write(buffer, 0, read);
}
out.flush();
out.close();
in.close();

//After the copy operation is finished we give execute permissions to iPerf3
File execFile = new File(executableFilePath);
execFile.setExecutable(true);

} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file: " + filename, e);
}
}

public static void executeIperf3() {

}

最佳答案

您尝试添加

String appFileDirectory = getFilesDir().getPath();
String executableFilePath = appFileDirectory + "/iperf3";

进入onCreate(),因为getFilesDir()是上下文方法。

关于java - Android getfilesdir() 中的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49104261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com