0

如果我尝试读取空白网页,我将如何返回默认字符串?

private void setVersion(String input) {
        try {
            URL url = new URL(input);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

            String getInfo;
            while ((getInfo = in.readLine()) != null) {
                Console("[setVersion Length]" + getInfo.length());
                dModVersionList.addElement(getInfo);
            }

        } catch (Exception e) {
            dModVersionList.addElement("Unknown");
            e.printStackTrace();
        }
    }

即使while循环返回null,我也想添加元素,如果页面不再存在,我已经可以处理它

4

3 回答 3

2

像这样的东西可以工作:

        String getInfo;
        // set initially to false
        boolean found = false;
        while ((getInfo = in.readLine()) != null) {
            found = true; // found some data; set to true
            Console("[setVersion Length]" + getInfo.length());
            dModVersionList.addElement(getInfo);
        }
        // still false; add your specific element
        if (!found)
            dModVersionList.addElement("no data");
于 2013-09-26T10:55:51.293 回答
1

试一试。

        while (true) {
            Console("[setVersion Length]" + getInfo.length());
            getInfo = in.readLine();
            if(getInfo.equals("exit")
               break;
            dModVersionList.addElement(getInfo);
        }
于 2013-09-26T10:56:18.567 回答
0

如果你的while循环返回null,意味着它不会进入你的loop,所以在你的循环之后你可以null检查getInfo然后设置String你想要的任何东西,你可以做类似的事情

                //local variable should be initialised.
                String getInfo = null;
                while ((getInfo = in.readLine()) != null) {
                    Console("[setVersion Length]" + getInfo.length());
                    dModVersionList.addElement(getInfo);
                }
                if(getInfo == null){
                   dModVersionList.addElement("Web page returns empty");
                }
于 2013-09-26T11:02:19.360 回答