register
other register

Friday, August 17, 2007

Retrieve a text file from a web address

Requirement:

Retrieve a text file from a web address and write it to a local file.



// Retrieve the web address from the property file, in which you can change the web address without changing the Java code

Properties properties = new Properties();
try {
properties.load(new FileInputStream("file.properties"));
} catch (IOException e){
System.out.println("Can't fild file.properties");
}
String webAddress= properties.getProperty("webAddress");

// Construct the url
URL url = new URL(webAddress);

// Establish the connection
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

// Retrieve the response status code
int statusCode = httpURLConnection.getResponseCode();

if (statusCode == 200){
// Create an empty file
File file = new File ("folderName" + "/" + "fileName" + ".extensionName");
if (file.exists()) {
file.delete();
}
// Create a buffered writer for output
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));


// Create a buffered reader to retrieve content from the web address
BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)httpURLConnection.getContent()));

String lLine = "";

// Read web content line by line and write it to the output file
while ((line = reader.readLine()) != null) {
output.append(line);
}

// Close the buffered writer
output.close();
}

No comments: