我有一个帮助我必须这样做,请不要发布代码,但是有人可以逻辑地向我解释如何将URL源代码保存为文本文件吗?
到目前为止,我有来自Oracle文档的代码:
import java.net.*;
import java.io.*;
public class URLConnectionReader {
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;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
所以这基本上是向我展示了控制台中的整个源代码,但是我想把它变成一个文本文件,然后我可以分析它来查找数据的趋势。
答案 0 :(得分:0)
我认为以下代码可以帮助您
public static void main(String[] args) throws IOException{
downloadFunction("http://google.com.vn",
"/tmp/google.html", "someHeaderValue");
}
private static void downloadFunction(String url, String outPut, String headerValue) throws IOException{
URL website = new URL(url);
URLConnection connection = website.openConnection();
connection.setRequestProperty("headerKey", headerValue);
InputStream response = connection.getInputStream();
ReadableByteChannel rbc = Channels.newChannel(response);
FileOutputStream fos = new FileOutputStream(outPut);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}