getfilesdir()中的Android空指针

时间:2018-03-05 05:53:21

标签: java android pointers null

我在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() {

}

1 个答案:

答案 0 :(得分:0)

您尝试添加

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

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