应用程序在写入文件时在模拟器中崩溃

时间:2017-09-09 20:00:22

标签: java android

我的应用程序(写入文件)在物理设备上正常工作..但在模拟器中崩溃。我用了

  makeFile = new 
 File(Environment.getExternalStorageDirectory().getAbsolutePath() 
  +  "/" +path);
  if (!makeFile.exists())
        makeFile.mkdirs();
     writeFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +path + File.separator + file_name + ".txt");

Log cat在这一行说错误

      bufferedWriter = new BufferedWriter(new FileWriter(writeFile, false));


 引起:java.lang.NullPointerException:尝试调用虚方法' void java.io.BufferedWriter.write(java.lang.String)'在null对象引用上 在这行代码

    bufferedWriter.write(contents);

我自己编写文件

的方法
enter code here
 public void writeSingleFile(String path, String file_name, String contents, boolean append) {
    makeFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +path);
    if (!makeFile.exists())
        makeFile.mkdirs();
    writeFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +path + File.separator + file_name + ".txt");
    try {
        if (append)
            bufferedWriter = new BufferedWriter(new FileWriter(writeFile, true));
        else
            bufferedWriter = new BufferedWriter(new FileWriter(writeFile, false));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if (append)
            bufferedWriter.write(contents + "\n");
        else
            bufferedWriter.write(contents);

    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        bufferedWriter.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:0)

 <?php
 if( $_POST )
{
   if( empty($_POST['file']) )
 {
   // echo error or do nothing;
   die("Select a file to upload");
     }
   }
 ?>
 <html>
 <body>
 <form action="" method="POST" enctype="multipart/form-data">
 <input type="file" name="image">
 <input type="submit" value="Submit">
 </form>
 </body>
 </html> 

首先,只需调用

即可省略第一个try { if (append) bufferedWriter = new BufferedWriter(new FileWriter(writeFile, true)); else bufferedWriter = new BufferedWriter(new FileWriter(writeFile, false)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 语句
if

如果实例化失败并出现异常,则只需在STDERR上输出并继续。在这种情况下,bufferedWriter会bufferedWriter = new BufferedWriter(new FileWriter(writeFile, append)); 进一步导致null。忽略异常是不好的,并且会导致你亲眼目睹的奇怪行为(充其量)。