我目前正在学习Java。我正在制作一个程序来获取给定 URL 的 html 代码,然后将代码保存为 *.html。在代码的末尾,我试图打印一条关于文件是否已保存的消息。
我的问题是确定文件是否已保存的布尔值始终返回 true。
这是我的代码:
public class URLClient {
protected URLConnection connection;
public static void main(String[] args){
URLClient client = new URLClient();
Scanner input = new Scanner(System.in);
String urlInput;
String fileName;
System.out.print("Please enter the URL of the web page you would like to download: ");
urlInput = input.next();
System.out.println("Save file As: ");
fileName = input.next();
String webPage = client.getDocumentAt(urlInput);
System.out.println(webPage);
writeToFile(webPage, fileName);
}
public String getDocumentAt (String urlString){
StringBuffer document = new StringBuffer();
try{
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + "\n");
reader.close();
}catch (MalformedURLException e){
System.out.println("Unable to connect to URL: " + urlString);
}catch (IOException e){
System.out.println("IOException when connectin to URL: " + urlString);
}
return document.toString();
}
public static void writeToFile(String content, String fileName){
boolean saved = false;
try{
OutputStream outputStream = new FileOutputStream(new File(fileName));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
try{
writer.write(content);
boolean saved = true;
} finally {
writer.close();
}
} catch (IOException e){
System.out.println("Caught exception while processing file: " + e.getMessage());
}
if (saved)
System.out.print("Successfully saved " + fileName + ".html");
}
}
布尔值称为“已保存”,位于 writeToFile() 方法中。
任何帮助将非常感激 :)