【发布时间】:2014-03-14 18:31:26
【问题描述】:
我正在尝试点击 URL 并尝试将 XML 文件保存到本地路径,但我无法做到。
我使用的代码在这里
公共类 T_save { 公共静态无效下载(字符串地址,字符串本地文件名){ 输出流输出 = null; URLConnection 连接 = 空; InputStream in = null;
try { URL url = new URL("url"); // URL url = new URL(address); conn = url.openConnection(); in = conn.getInputStream();
File file = new File(address+localFileName);
FileWriter fileWriter = new FileWriter(file);
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
fileWriter.write(line);
}
fileWriter.flush();
fileWriter.close();
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
}
}
}
public static void download(String address) {
int lastSlashIndex = address.lastIndexOf('\');
if (lastSlashIndex >= 0 && lastSlashIndex < address.length() - 1) {
System.out.println(address.substring(0, lastSlashIndex+1)+"\t\t\t"+
address.substring(lastSlashIndex + 1));
download(address.substring(0, lastSlashIndex+1), address.substring
(lastSlashIndex + 1));
} else {
System.err.println("Could not figure out local file name for "
+ address);
}
}
public static void main(String[] args) {
download("C:\\Users\\praveen\\chaithu12.xml");}
/*
* for (int i = 0; i < args.length; i++) { download(args[i]); }
*/
public static class CustomAuthenticator extends Authenticator {
// for entering password
protected PasswordAuthentication getPasswordAuthentication() {
// Get information about the request
String prompt = getRequestingPrompt();
String hostname = getRequestingHost();
InetAddress ipaddr = getRequestingSite();
int port = getRequestingPort();
String username = "username";
String password = "password";
// Return the information (a data holder that is used by Authenticator)
return new PasswordAuthentication(username, password.toCharArray());
}
}
}
【问题讨论】:
-
有没有其他方法可以将输入流保存到本地路径的xml文件中
-
还有其他方法吗??
标签: xml