使用Java将任何URL的HTML内容保存在文本文件中

时间:2014-03-17 21:25:03

标签: java url

我试图将任何URL的HTML内容保存为java中的文本文件,但它不起作用如何保存? 我的代码是

import java.io.*;

class DemoTest {
    public static void main(String st[]) {
        try {
            FileInputStream fis = new FileInputStream("C:\Users\Admin\Desktop\new.html");
            //a.html or pass tha path of html
            FileOutputStream fos = new FileOutputStream("b.txt");//to writw source in file
            while (true) {
                int i = fis.read();
                if (i == -1)
                    break;
                System.out.print((char) i);//display on cmd
                fos.write(i);// write the source in b.txt

            }
        } catch (Exception e) {
        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用Files.copy()

Files.copy(Paths.get(sourceFile), Paths.get(dstFile));

如果您有URL个对象,则可以直接复制其流:

Files.copy(url.openStream(), Paths.get(dstFile));

Javadoc for Files

答案 1 :(得分:0)

PrintWriter writer = new PrintWriter("fileName.txt");
//for each line in the HTML content, read it in as a string variable
writer.println(lineStringVariable);
writer.close();