File.createNewFile()的结果被忽略

时间:2018-10-13 11:25:31

标签: java android

请我帮你找出我做错了什么。使用android studio创建文件时遇到问题。 没有错误,但是未创建文件“ textstring.txt”。 W / System.err:java.io.IOException:打开失败:ENOENT(没有这样的文件或目录)并且 W / System.err:我收到的警告是java.io.File.createNewFile(File.java:944),它发生在myFile.createNewFile()

这是我的代码行

private String INPUT_FILE = "textstring.txt";
private String inputString = "thisIsTheTextToWrite";

private File myFile = null;

private Button myWrite = null;

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

    //Create a file
    myFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/Data/" + getPackageName() + "/files/" + INPUT_FILE);

    mWrite = (Button)findViewById(R.id.b_write);
    mWrite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                FileOutputStream output = openFileOutput(INPUT_FILE, MODE_PRIVATE);
                output.write(inputString.getBytes());

                if(output != null)
                    output.close();

                //
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                        && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()))
                {
                    myFile.createNewFile();
                    output = new FileOutputStream(myFile);
                    output.write(inputString.getBytes());

                    if(output != null)
                        output.close();
                }
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    });
}

}

问题似乎发生在// myFile.createNewFile();。 为什么 ? 预先谢谢你

1 个答案:

答案 0 :(得分:-1)

这只是警告吗?

您应始终检查myFile.createNewFile()的结果:

if(!myFile.createNewFile()) {
    Log.e("mDebug", "Couldn't create the file");
}

就这样