亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java "while != null" 讀取最后一行為 null

Java "while != null" 讀取最后一行為 null

森林海 2023-03-02 10:23:45
我正在嘗試使用 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);                } 
查看完整描述

1 回答

?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

檢查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);

    ...


查看完整回答
反對 回復 2023-03-02
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號