我想知道如何将我的InputStream内容写入XML文件(android)

时间:2011-06-07 11:11:48

标签: java android xml input

嘿,我有以下代码:

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文件中?请帮忙

2 个答案:

答案 0 :(得分: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();

将输入流放入缓冲区并读取它:

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

答案 1 :(得分: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();
    }
}