-1

我目前正在学习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() 方法中。

任何帮助将非常感激 :)

4

2 回答 2

3
try {
    writer.write(content);
    saved = true; // no need to initialize again
} finally {
    writer.close();
}
于 2013-03-26T19:36:47.850 回答
0

那么您需要了解局部变量和全局变量的概念。您已经用相同的数据类型初始化了两次相同的变量名。我已经为您相应地更改了代码。

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);
        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");
}
于 2013-03-26T19:38:00.370 回答