这是我的代码,我在函数 writeFile() 中得到 NPE。关键是将字符串传递给 writeFile() 方法,然后使用 createFile() 创建文件并将字符串写入新创建的文件。
该文件已在目录中成功创建,但没有写入任何内容。该字符串也在 Logcat 上显示输出,因此很明显它不是一个空字符串。
public File createFile( ){
File storageLocation = new File( Environment.getExternalStorageDirectory(), path);
storageLocation.mkdirs();
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(context, "Cannot use storage.", Toast.LENGTH_SHORT).show();
}
try{
File file = new File(storageLocation, getFileName()+".xml");
file.createNewFile();
}
catch( IOException e){
e.printStackTrace();
}
return file;
}
public String getFileName( ){
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyy",Locale.UK);
return sdf.format(c.getTime( ));
}
public void writeFile( String text ){
try{
line 56>> FileOutputStream fos = new FileOutputStream( createFile( ).getAbsoluteFile());
out = new DataOutputStream(fos);
out.writeUTF(text);
Toast.makeText(context.getApplicationContext(), "Backup Successfull.", Toast.LENGTH_LONG).show();
out.close();
}
catch( IOException e){
e.printStackTrace();
Toast.makeText(context.getApplicationContext(), "Backup Failed.", Toast.LENGTH_LONG).show();
}
catch( NullPointerException e){
e.printStackTrace();
Toast.makeText(context.getApplicationContext(), "Backup Failed.", Toast.LENGTH_LONG).show();
}
}
编辑:权限设置为
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这是来自 Logcat 的日志:
05-04 09:21:47.276: W/System.err(1137): java.lang.NullPointerException
05-04 09:21:47.286: W/System.err(1137): at com.codepalette.ceeq.FileManager.writeFile(FileManager.java:56)
05-04 09:21:47.286: W/System.err(1137): at com.codepalette.ceeq.BackupManager.backCallLogs(BackupManager.java:50)
05-04 09:21:47.286: W/System.err(1137): at com.codepalette.ceeq.BackupManager.takeBackup(BackupManager.java:25)
05-04 09:21:47.296: W/System.err(1137): at com.codepalette.ceeq.Home$2.onClick(Home.java:154)