I want know how I can write my InputStream content to an XML file (android)
Hey I have the following code:
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 ((inputLin开发者_如何学Goe = 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);
}
}
}
How can i save the source code i get from this to a XML file? Please help
Create a Connection:
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();
Put inputstream in a buffer and read it:
BufferedReader r = new BufferedReader(new InputStreamReader(is2));
total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Then put it in the file:
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();
Hope this helpes
Here is an example, where "iso" is you 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();
}
}
精彩评论