任何人都可以帮助我使用Java URL阅读器吗?
我在Java中创建了一个URL阅读器,用于读取链接并将其发送到特定文件。 如何从两个URL读取代码并将其保存到特定文件中?
这是我的代码:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
BufferedWriter psout = new BufferedWriter(new FileWriter("D:\\final.txt"));
while ((inputLine = in.readLine()) != null) {
psout.write(inputLine);
System.out.println(inputLine);
}
in.close();
psout.close();
}
}
答案 0 :(得分:0)
如果您打算写入单个文件,可以将其解压缩到方法中并使用append
中的FileWriter
参数:
private static void saveURL(String urlString) throws MalformedURLException, IOException {
URL url = new URL(urlString);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
BufferedWriter psout = new BufferedWriter(new FileWriter("final.txt", true));
// write file...
}
答案 1 :(得分:0)
如果我理解你的问题,你想把两个不同URL的内容写入同一个文件。您可以拥有一个URL对象列表,然后通过列表读取/写入迭代。
List<URL> al = new ArrayList<>();
URL oracle = new URL("http://www.oracle.com/");
URL google =new URL("http://www.google.com");
al.add(oracle);
al.add(google);
BufferedReader in=null;
BufferedWriter psout=null;
for(URL url: al){
URLConnection yc = url.openConnection();
in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
psout = new BufferedWriter(new FileWriter("final.txt"));
while ((inputLine = in.readLine()) != null) {
psout.write(inputLine);
System.out.println(inputLine);
}
} in.close();
psout.close();