boolean总是返回true

时间:2013-03-26 19:33:46

标签: java boolean

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

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:3)

try {
    writer.write(content);
    saved = true; // no need to initialize again
} finally {
    writer.close();
}

答案 1 :(得分:0)

您需要了解Local和Global变量的概念。您已使用相同的数据类型初始化了两次相同的变量名称。我已经相应地更改了代码。

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");
}