NullPointerException Occurs when trying to create a file and write data to it in Android
I am trying to create a file ,if it doesnot exist and tried to write some data to it. The same program I did in java, it was running fine.But when I try to do the same thing in Android I am getting NullPointerException at the place where I am trying to write data to file. And also, I did not find any new file in the current directory .I will share the code here:
xmlpoc.java
public class xmlPoc extends Activity {
String s="<employee>"+
"<details>"+
"<pictag id="+
"\"@drawable/icon\"" +
"mystr"+
"="+
"\"Picture 1\"" +
"myint" +
" =" +
"\"33\"" +
"/>"+
" <name>SandeepKumarSuman</name>"+
"<designation>J2ME Programmer</designation>"+
"<city>Gorakhpur</city>"+
"<state>UP</state>"+
"<name>mohan</name>"+
"<designation>J2ME GAMEProgrammer</designation>"+
"<city>HYD</city>"+
"<state>AP</state>"+
"<name>hari</name>"+
"<designation>Fresher</designation>"+
"<city>GNT</city>"+
"<state>AP</state>"+
"</details>"+
"</employee>";
File f;
FileOutputStream fop;
@Override
public void onCreate(Bundle savedInstanceStat开发者_Go百科e) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
f=new File("./myfile1.txt");
try {
fop=new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("New file myfile.txt has been created to the current directory");
}
try {
fop.write(s.getBytes());
fop.flush();
fop.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone help me in sorting out this issue.
Thanks in Advance,
}Check out the android dev guide here, and if you want to write to the external storage you should add the permissions to your manifest and use "getExternalStorageDirectory()", or "getExternalFilesDir()" if you are using API 8 or higher. You can't just write everywhere, that's why you need to use androids "openFileOutput(" or just write to the external storage.
External storage permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try f=new File("myfile1.txt");
精彩评论