2011-06-07 65 views
0

嘿,我有以下代碼:我想知道我怎麼可以在我的InputStream的內容寫入到一個XML文件(機器人)

import java.net.*; 
import java.io.*; 

class OpenStreamTest { 
public static void main(String args[]) { 
    try { 
     URL yahoo = new URL("http://www.yahoo.com/"); 
     DataInputStream dis; 
     String inputLine; 

     dis = new DataInputStream(yahoo.openStream()); 
     while ((inputLine = dis.readLine()) != null) { 
      System.out.println(inputLine); 
     } 
     dis.close(); 
    } catch (MalformedURLException me) { 
     System.out.println("MalformedURLException: " + me); 
    } catch (IOException ioe) { 
     System.out.println("IOException: " + ioe); 
    } 
} 
} 

我怎麼能在源代碼中,我從這個得到保存到一個XML文件?請幫助

回答

0

創建連接:

DefaultHttpClient httpclient = new DefaultHttpClient(); 
HttpGet httppost = new HttpGet("http://www.google.com"); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity ht = response.getEntity(); 
BufferedHttpEntity buf = new BufferedHttpEntity(ht); 
InputStream is = buf.getContent(); 

看跌的InputStream在緩衝區和閱讀:

BufferedReader r = new BufferedReader(new InputStreamReader(is2)); 
total = new StringBuilder(); 
String line; 
while ((line = r.readLine()) != null) { 
    total.append(line); 
} 

然後把它在文件中:

File file = new File("/sdcard", "report.xml"); 
if(!file.exists()){ 
    file.createNewFile(); 
} 

StringBuilder temp = null; 
while ((inputLine = dis.readLine()) != null) { 
    temp.append(inputLine); 
} 

FileWriter fw = new FileWriter(file); 
fw.write(temp.toString()); 
fw.flush(); 

希望這helpes

+0

不是真的,因爲Android java有點不同。 – aris 2011-06-07 11:49:14

+0

你有沒有試過?,我在我的Android應用程序中使用此代碼,沒有錯誤... – BadSkillz 2011-06-07 11:54:54

+0

那我在第一行(我做的是Android 2.1)出現錯誤 你可以請c/p整個代碼,你有?你可以請加我MSN或Skype進一步幫助? :( – aris 2011-06-07 11:58:27

0

這裏是一個例子,其中「iso」就是你InputSrteam

try { 
    final File file = new File("/sdcard/filename.xml"); 
    final OutputStream output = new FileOutputStream(file); 

    try { 
     try { 
      final byte[] buffer = new byte[1024]; 
      int read; 

      while ((read = iso.read(buffer)) != -1) 
       output.write(buffer, 0, read); 

      output.flush(); 
     } 
     finally { 
      output.close(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} finally { 
    try { 
     iso.close(); 
     System.out.println("saved"); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
+0

記得添加SDcard存儲使用權限! – 2013-03-11 13:29:54

相關問題