您的位置:首页 > 理论基础 > 计算机网络

用java从网络上抓取HTML文件内容并写入本地文本中

2009-03-18 15:24 691 查看
package Tech;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class GetHtmlFile {

/**
* @param args
* @throws IOException
* @throws URISyntaxException
*/
public static void main(String[] args) throws IOException, URISyntaxException {
// TODO Auto-generated method stub
URL url= new URL("http://www.163.com");
InputStream is = url.openStream();
//OutputStream ois= url.openConnection().getOutputStream();
File file = new File(new URI("file:/c:/g3.txt"));
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int ch;
while((ch=is.read())!=-1)
{
bos.write(ch);
bos.flush();
//System.out.print((char)ch);
}

}

}


代码都是些基础代码,不过那个本地File的URI的创建搞了我很长时间,在网上也没搜到啥··

先后试过:

new URI("file://C://g.txt")

Exception:Illegal character in authority

new URI("file://C:/g.txt")

Exception:URI has an authority component

最后试出了结果

new URI("file:/c:/g3.txt")

最后从有关书籍上查得,正解应该是这样的.

URL url = new URL("file://" + realPath); //for Linux
URL url = new URL("file:///" + realPath); //for Windows
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: