2011-09-12 75 views
0

我想從res/xml文件夾複製一個xml文件到設備存儲,但我真的很努力如何做到這一點。從Res/Xml文件夾複製Xml文件到設備存儲

我知道起點是得到一個InputStream來讀取xml文件。這是通過使用這個實現:

InputStream is = getResources().openRawResource(R.xml.xmlfile); 

最終輸出流將是:

file = new File("xmlfile.xml"); 
FileOutputStream fileOutputStream = new FileOutputStream(file); 

但我真的很掙扎如何閱讀,並從最初的XML文件正確複製所有的信息和準確。

到目前爲止,我利用各種InputStreamOutputStream讀寫(DataInputStreamDataOutputStreamOutputStreamWriter等)做過嘗試,但我仍然沒有設法正確地得到它。在生成的xml文件中有一些未知字符(編碼問題?)。誰可以幫我這個事?謝謝!

回答

0

res/xml你不能,你必須把所有的文件在您的assets文件夾,然後下面的代碼

Resources r = getResources(); 
AssetManager assetManager = r.getAssets(); 

File f = new File(Environment.getExternalStorageDirectory(), "dummy.xml"); 
InputStream is = = assetManager.open("fileinAssestFolder.xml"); 
OutputStream os = new FileOutputStream(f, true); 

final int buffer_size = 1024 * 1024; 
try 
{ 
    byte[] bytes = new byte[buffer_size]; 
    for (;;) 
    { 
     int count = is.read(bytes, 0, buffer_size); 
     if (count == -1) 
      break; 
     os.write(bytes, 0, count); 
    } 
    is.close(); 
    os.close(); 
} 
catch (Exception ex) 
{ 
    ex.printStackTrace(); 
} 
+0

它的工作原理,這部分......能不能請你爲什麼這樣BUFFER_SIZE解釋一下嗎?並且可以詳細說明for循環。我嘗試過使用你的方法和其他幾個,但它似乎是新創建的xml要麼更短,要麼更長..即時通訊仍然不知道爲什麼我不能得到原來的確切的XML。 – ImpStudent

+0

解決了!感謝:D – ImpStudent

0

您也可以使用此代碼:

try { 
     InputStream input = getResources().openRawResource(R.raw.XZY); 
     OutputStream output = getApplicationContext().openFileOutput("xyz.mp3", Context.MODE_PRIVATE); 
     byte data[] = new byte[1024]; 
     long total = 0; 
     int count; 
     while ((count = input.read(data)) != -1) { 
      total += count; 
      output.write(data, 0, count); 
     } 
     output.flush(); 
     output.close(); 
     input.close(); 
    } catch (Exception e) { 
    } 

而當你需要的文件使用此代碼:

File k =getApplicationContext().getFileStreamPath("xyz.mp3"); 
相關問題