Reputation: 65
What I wanna do is get the content of this URL :
and copy it to a file so I can parse it and use the elements.
Here is what I have so far :
package test;
import java.io.*;
import java.net.*;
import org.apache.commons.io.FileUtils;
public class JavaGetUrl {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws FileNotFoundException {
URL u;
InputStream is = null;
DataInputStream dis;
String s = null;
try {
u = new URL(
"https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=CYQB&hoursBeforeNow=2");
is = u.openStream(); // throws an IOException
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null) {
System.out.println(s);
FileUtils.writeStringToFile(new File("input.txt"), s);
}
} catch (MalformedURLException mue) {
System.out.println("Ouch - a MalformedURLException happened.");
mue.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
System.out.println("Oops- an IOException happened.");
ioe.printStackTrace();
System.exit(1);
} finally {
try {
is.close();
} catch (IOException ioe) {
}
}
}
}
The problem is that the content of s does not show up in input.txt.
If I replace s by any other strings it works. So I guess it's a problem with the data of s. Is it because it's xml?
Thank you all for the help.
Upvotes: 0
Views: 1357
Reputation: 18459
The file is probably getting over-written.
You should use "append" mode to get file appended with data(from readLine).
public static void writeStringToFile(File file,
String data,
boolean append)
Upvotes: 3
Reputation: 2090
as you are already using apaches commons-io, you can also simply use
FileUtils.copyURLToFile(URL, File)
Upvotes: 0