帮助做这样的事情,我们有一个文本文件,有很多不同网站的链接(每个链接 rasolozhena 一个新行,它们以http://test.com的形式写),你需要走在Java程序上将这些站点的所有页面链接并保存在文件夹C://test中,并以html格式保存这些页面的名称与标签中的名称相同
问问题
88 次
3 回答
1
正如您在问题中描述的那样,这是从 txt 文件中读取 URL 并写入另一个文件的代码。
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("urlList.txt")));
String url = reader.readLine();
int i = 0;
while (url != null) {
try {
getContent(url, i);
} catch (IOException io) {
System.out.println(io);
}
i++;
url = reader.readLine();
}
} catch (IOException io) {
System.out.println(io);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// nothing
}
}
}
}
private static void getContent(String url, int index)
throws MalformedURLException, IOException {
URL pageUrl;
URLConnection conn = null;
pageUrl = new URL(url);
conn = pageUrl.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader reader = new BufferedReader(in);
String htmlFileName = "file_content_" + index + ".txt";
FileWriter fWriter = new FileWriter(htmlFileName);
BufferedWriter bWriter = new BufferedWriter(fWriter);
String urlData = null;
while ((urlData = reader.readLine()) != null) {
bWriter.write(urlData);
bWriter.newLine();
}
bWriter.close();
}
于 2012-11-19T13:15:54.393 回答
0
public class URLReader
{
public static void main(String[] args)
{
try
{
URL pageUrl;
URLConnection conn = null;
pageUrl = new URL("https://www.google.ru/");
conn = pageUrl.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader reader = new BufferedReader(in);
String htmlFileName = "C:\\hello.html";
FileWriter fWriter = new FileWriter(htmlFileName);
BufferedWriter bWriter = new BufferedWriter(fWriter);
String urlData = null;
while ((urlData = reader.readLine()) != null)
{
bWriter.write(urlData);
bWriter.newLine();
}
bWriter.close();
}
catch(IOException io)
{
System.out.println(io);
}
}
}
@Victor这是一个开始,您可以改进代码,一切都像我在问题中描述的那样?请
于 2012-11-19T14:29:15.793 回答
0
我前段时间问过类似的问题:Reading website's contents into string
您可以将其复制到 some 中,而不是将其读入字符串FileOutputStream
。Apache Commons 中有一个很好的功能IOUtils
:
copy(InputStream input, OutputStream output)
Copy bytes from an InputStream to an OutputStream.
http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html
如果你也想在你的页面上下载图片和其他文件,你最好使用一些库。
当然,如果你正在学习,你可以自己实现。正则表达式可用于查找 HTML 文件中的图像链接。
于 2012-11-19T14:34:37.667 回答