gpt4 book ai didi

android - createNewFile() 抛出错误

转载 作者:行者123 更新时间:2023-11-29 14:41:46 24 4
gpt4 key购买 nike

在我的 android 应用程序中,我尝试在 sdcard 上创建一个 xml 文件。我试过这个:

public class XmlFileCreator extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


System.out.println(Environment.getExternalStorageDirectory());
// create a new file called "new.xml" in the SD card
File newxmlfile = new File( Environment.getExternalStorageDirectory(),"new.xml");
try {
newxmlfile.createNewFile();
} catch (IOException e) {
Log.e("IOException", "exception in createNewFile() method");
}

FileOutputStream fileos = null;
try {
fileos = new FileOutputStream(newxmlfile);
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
// we create a XmlSerializer in order to write xml data
XmlSerializer serializer = Xml.newSerializer();

try {
// we set the FileOutputStream as output for the serializer, using
// UTF-8 encoding
serializer.setOutput(fileos, "UTF-8");
// Write <?xml declaration with encoding (if encoding not null) and
// standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
// set indentation option
serializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output",
true);
// start a tag called "root"
serializer.startTag(null, "root");
// i indent code just to have a view similar to xml-tree
serializer.startTag(null, "child1");
serializer.endTag(null, "child1");
serializer.startTag(null, "child2");
// set an attribute called "attribute" with a "value" for <child2>
serializer.attribute(null, "attribute", "value");
serializer.endTag(null, "child2");

serializer.startTag(null, "child3");
// write some text inside <child3>
serializer.text("some text inside child3");
serializer.endTag(null, "child3");

serializer.endTag(null, "root");
serializer.endDocument();
// write xml data into the FileOutputStream
serializer.flush();
// finally we close the file stream
fileos.close();

System.out.println("file has been created on SD card");
}
catch(Exception e){
Log.e("Exception","error occurred while creating xml file");
}
}
}

但是在 LogCat 中我得到了这个:

08-23 11:19:56.776: ERROR/IOException(6333): exception in createNewFile() method
08-23 11:19:56.776: ERROR/FileNotFoundException(6333): can't create FileOutputStream
08-23 11:19:56.776: ERROR/Exception(6333): error occurred while creating xml file

问题出在哪里?为什么 createNewFile() 抛出 IOException?需要一些帮助,请...

最佳答案

File newxmlfile = new File( Environment.getExternalStorageDirectory()+"/new.xml");

明确许可

< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 

关于android - createNewFile() 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7158112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com