我在Android中创建xml文件时出错

时间:2017-06-02 15:37:32

标签: java android xml

我有以下代码创建一个xml文件并将其保存在设备中。

package com.ex.createXml;

import android.app.Activity;
import android.os.Bundle;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xmlpull.v1.XmlSerializer;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.widget.TextView;


public class createXml extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_create_xml);

  File newxmlfile = new File("/sdcard/Downloads/new.xml");
  try {
   newxmlfile.createNewFile();
  } catch (IOException e) {
   Log.e("IOException", "Exception in create new File(");
  }
  FileOutputStream fileos = null;
  try {
   fileos = new FileOutputStream(newxmlfile);
  } catch (FileNotFoundException e) {
   Log.e("FileNotFoundException", e.toString());
  }
  XmlSerializer serializer = Xml.newSerializer();
  try {
   serializer.setOutput(fileos, "UTF-8");
   serializer.startDocument(null, Boolean.valueOf(true));
   serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent- output", true);
   serializer.startTag(null, "root");
   serializer.startTag(null, "Child1");
   serializer.endTag(null, "Child1");
   serializer.startTag(null, "Child2");
   serializer.attribute(null, "attribute", "value");
   serializer.endTag(null, "Child2");
   serializer.startTag(null, "Child3");
   serializer.text("Some text inside child 3");
   serializer.endTag(null, "Child3");
   serializer.endTag(null, "root");
   serializer.endDocument();
   serializer.flush();
   fileos.close();
   //TextView tv = (TextView)findViewById(R.);

  } catch (Exception e) {
   Log.e("Exception", "Exception occured in wroting");
  }
 }
}

当我运行应用程序时,我收到了这些错误

06-02 15:20:03.753 2530-2530/com.ex.createXml E/IOException:        Exception in create new File(
06-02 15:20:03.753 2530-2530/com.ex.createXml   E/FileNotFoundException: java.io.FileNotFoundException:    /sdcard/Downloads/new.xml (No such file or directory)
06-02 15:20:03.753 2530-2530/com.ex.createXml E/Exception: Exception    occured in wroting

我已将这些权限添加到清单

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

其中一个错误是/sdcard/Downloads/new.xml(没有这样的文件或目录)。你可以给我一个正确的路径来保存我的文件或任何其他错误的想法吗?谢谢

1 个答案:

答案 0 :(得分:0)

您必须确保根SD卡存在。尝试使用Environment.getExternalStorageDirectory()来获取外部目录而不是静态路径/ sdcard。如果要使用静态路径,请打印Environment.getExternalStorageDirectory()以查看外部存储的根目录