Java "while != null"将最后一行读取为空

标签 java

我尝试使用 URL 批处理文件运行以下代码,但 URL 不为空。它完全按照我想要的方式运行,但是,输出的最后一行显示:

格式错误的 URL 异常:“null”不是有效的输入

批量计划成功完成

我希望程序在实际读取 null 之前停止。有什么建议吗?

(另外,我仍在学习如何提问而不让人们生我的气,所以如果我可以改进我的问题,请告诉我而不是否决。谢谢。)

private static String getBatchUrlContents(String filePath) {
        logger.debug(">>getBatchUrlContents()");
        String theUrl = "";
        try {
            FileReader fileReader = new FileReader(filePath);
            BufferedReader bufferedUrlReader = new BufferedReader(fileReader);
            do {
                try {
                    theUrl = bufferedUrlReader.readLine();
                    URL url = new URL(theUrl);
                    HttpURLConnection urlConnection = (HttpURLConnection)  url.openConnection();

                urlConnection.setRequestMethod("GET");
                String contentType = urlConnection.getContentType();
                logger.info("Content Type: {}", contentType);
                int statusCode = urlConnection.getResponseCode();
                logger.info("Status Code: {}", statusCode);


                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line;

                List<String> contents = new ArrayList<String>(); 
                while ((line = bufferedReader.readLine()) != null) {
                    contents.add(line);
                }
                bufferedReader.close();
                String[] contentArray = contents.toArray(new String[contents.size()]);
                System.out.println("\n ~~~~~~~NEW URL~~~~~~~ \n" + theUrl);
                for (String x :contentArray)
                    System.out.println(x);

                String firstLine = contentArray[0];

                if (firstLine.equals("#EXTM3U")) {
                    logger.info("First line is validated: {}", firstLine);
                    System.out.println("First line of content is validated: " + firstLine);
                } else {
                    logger.error("Error: First line not valid: {}", firstLine);
                    System.out.println("Error: First line reads: '" + firstLine + "'\n"
                            + "Should read: '#EXTM3U'");
                }

            } catch(Exception e) {
                if (e instanceof MalformedURLException) {
                    logger.error("Malformed URL Exception: {}", e.toString());
                    System.out.println("Malformed URL Exception: '" + theUrl + "' is not a valid input");
                } else if (e instanceof FileNotFoundException) {
                    logger.error("404: File Not Found Exception: {}", e.toString());
                    System.out.println("Unable to open URL: " + theUrl);
                } else if (e instanceof IOException) {
                    logger.error("IO Exception: {}", e.toString());
                    System.out.println("Error reading file: " + theUrl);
                } else {
                    logger.error("Exception: {}", e.toString());
                    System.out.println("Exception Error - Unable to read or open: " + theUrl);
                }
            }
        } while (theUrl != null);
        bufferedUrlReader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Unable to open file '" + filePath + "'");
        System.exit(2);
    } catch (IOException ex) {
        System.out.println("Error reading file '" + filePath + "'");
        System.exit(3);
    }
    logger.debug("<<getUrlContents()");
    return "Batch Program Completed Successfully";
}

最佳答案

theUrl != null 检查发生在循环结束时;它不会被连续检查。

如果您需要 theURL 为非 null,则需要进行检查。

您可以在以下条件下进行分配(尽管这在某些圈子中是不受欢迎的):

while((theUrl = bufferedUrlReader.readLine()) != null) {
    URL url = new URL(theUrl);
    ...

或者,只需在循环内进行检查并执行手动break:

while(true) {
    theUrl = bufferedUrlReader.readLine();

    if (!theURL) { // Or "if (theURL == null)"
        break;
    }

    URL url = new URL(theUrl);
    ...

关于Java "while != null"将最后一行读取为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837346/

相关文章:

使用线框生成 Java 代码

java - 如何在 BroadcastReceiver 中访问 MainActivity 的对象或方法?

java - 如何在 Android 中实现登录弹出对话框,直到注销才弹出?

java - 泛型数组转换

java - 用solr构建标签云

java - 即使我得到了正确的名称和路径,Zip 文件也没有被删除

java - 来自 url 的 android png 的透明度显示为黑色

JavaFX 模块对 VM 不可见

java - 从资源文件夹中获取 Json 文件

java - 使用 Java 的 Path2D 创建钢笔工具的问题