如果url页面为空,则返回另一个String

时间:2013-09-26 10:53:23

标签: java

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

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,如果页面不再存在,我已经可以处理它了

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:1)

试一试。

        while (true) {
            Console("[setVersion Length]" + getInfo.length());
            getInfo = in.readLine();
            if(getInfo.equals("exit")
               break;
            dModVersionList.addElement(getInfo);
        }

答案 2 :(得分: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");
                }