2014-03-04 48 views
1

我想這個代碼,但我不知道我在哪裏可以找到創建創建採用Android

public class MainActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    //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"); 
    } 

    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"); 
      //write some text inside <child3> 
      serializer.text("some text inside child3"); 
      serializer.endTag(null, "child3"); 

     serializer.endTag(null, "root"); 
     serializer.endDocument(); 
     serializer.flush(); 
     fileos.close(); 

      TextView tv = (TextView)this.findViewById(R.id.result); 
      tv.setText("file has been created on SD card"); 
      System.out.println("file created"); 
    } catch (Exception e) { 
     Log.e("Exception","error occurred while creating xml file"); 
    } 
    } 
    } 
+0

它應和在SD卡/ new.xml問題。 See:[Environment.getExternalStorageDirectory()](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29) –

回答

0

它不同與手機的型號,並且如果您有任何外部的XML文件中的XML文件存儲。 檢查文件路徑的最佳方法是在您的應用程序中執行此操作。您應該使用:

String path = newxmlfile.getAbsolutePath(); 
0

文件必須在SD卡中創建,如果你不覺得那有代碼

+0

我發現它終於:) thkx所有 – Marya

+0

偉大的: ) 祝你好運 ;) – user2689294