我目前正在學習Java。我正在製作一個程序來獲取給定URL的html代碼,然後將代碼保存爲* .html。在代碼的最後,我試圖打印一條消息,確定該文件是否已保存。布爾總是返回true
我的問題是,確定文件是否已保存的布爾總是返回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()方法。
任何幫助,將不勝感激:)
內部'saved'不應該在它前面有'boolean'。你把外面的'保存'超出了範圍,這是暫時的陰影。 'saved = true',而不是'boolean saved = true'。 – pickypg 2013-03-26 19:35:35
在'try'裏面的'saved'之前刪除'boolean'' – Maroun 2013-03-26 19:35:41
從'boolean saved = true;'中刪除'boolean''但是你不使用任何IDE?因爲這應該表明你編譯錯誤 – Tako 2013-03-26 19:37:22