PrintStream不会创建新文件

时间:2017-04-24 16:14:35

标签: java android compiler-errors

以下代码甚至在编译之前提供了一个文件未找到异常(隐藏在 openFileOutpu t位)。我已更改清单以允许外部存储写入和读取权限。任何帮助将不胜感激!

    public void AddWordMethod(View view) {

            EditText NameEdit = (EditText)findViewById(R.id.NewWordID);
            String NewName = NameEdit.getText().toString();
            EditText SurnameEdit =  
               (EditText)findViewById(R.id.NewSurnameID);
            String NewSurname = NameEdit.getText().toString();

    PrintStream output = new PrintStream(openFileOutput("added_names.txt", MODE_PRIVATE));
    output.println(NewName + "\t" + NewSurname);
    output.close();}}

1 个答案:

答案 0 :(得分:0)

在Java中,每个Exception必须用try catch包装。你在代码中看到的红线是编译器错误告诉你,你没有把try catch放到位。

尝试休闲:

public void AddWordMethod(View view) {

    EditText NameEdit = (EditText) findViewById(R.id.NewWordID);
    String NewName = NameEdit.getText().toString();
    EditText SurnameEdit =
            (EditText) findViewById(R.id.NewSurnameID);
    String NewSurname = NameEdit.getText().toString();

    PrintStream output = null;
    try {
        output = new PrintStream(openFileOutput("added_names.txt", MODE_PRIVATE));
    } catch (Exception e) {
        e.printStackTrace();
    }
    output.println(NewName + "\t" + NewSurname);
    output.close();
}