2011-06-07 63 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

相关问题