Java“ while!= null”将最后一行读取为null

时间:2019-07-01 14:20:21

标签: java

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

格式错误的URL异常:'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";
}

1 个答案:

答案 0 :(得分:1)

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);
    ...