我正在尝试创建一个文件,如果它不存在并尝试向其写入一些数据。我在java中做的程序相同,运行正常。但是当我尝试在Android中做同样的事情时,我在我试图将数据写入文件的地方得到NullPointerException。而且,我没有在当前目录中找到任何新文件。我将在此处共享代码:
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 savedInstanceState) {
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();
}
}
任何人都可以帮我解决这个问题。
提前致谢,
}
答案 0 :(得分:1)
查看android开发指南here,如果你想写入外部存储,你应该为你的清单添加权限,并使用“getExternalStorageDirectory()”或“getExternalFilesDir()”如果你是使用API 8或更高版本。你不能只是到处写,这就是为什么你需要使用orroids“openFileOutput(”或只是写入外部存储器。
外部存储权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
答案 1 :(得分:0)
尝试f=new File("myfile1.txt");