私は現在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() メソッドにあります。
どんな助けでも大歓迎です:)