The following code saves the page’s content to a file:
import java.net.*;
import java.io.*;
public class url
{
public static void main(String[] args)
{
try
{
URL PageUrl;
URLConnection GetConn = null;
GetConn = null;
PageUrl = new URL("https://www.google.ru/");
GetConn = PageUrl.openConnection();
GetConn.connect();
InputStreamReader ReadIn = new InputStreamReader(GetConn.getInputStream());
BufferedReader BufData = new BufferedReader(ReadIn);
String htmlFileName = ("C:\\hello.html");
FileWriter FWriter = new FileWriter(htmlFileName);
BufferedWriter BWriter = new BufferedWriter(FWriter);
String UrlData = null;
while ((UrlData = BufData.readLine()) != null)
{
BWriter.write(UrlData);
BWriter.newLine();
}
BWriter.close();
}
catch(IOException io)
{
System.out.println(io);
}
}
}
But I need the file have the same name as the page of the website, for example, it has to somehow get the name of the web page and assign it as the file’s name.
You can use URL.getFile() to get the filename. I.e
Note that different URLs may refer to the same file:
http://example.com/test.html#anch1,http://example.com/test.html,http://example.com/test.html?a=b– all three refer to the sametest.htmlfile here. In this case you might want to combinegetFile(),getRef()andgetQuery()somehow.It is worth to mention some issues in your code:
lowerCaseinstead ofUpperCase;finallyblocks. Better, if you use Java 7, use try-with-resources.