引用 这个读文件后输出,最后的wrong doing 怎么一直有,怎么才可以在正常读文件 的最后不运行那一个语句:

引用 这个读文件后输出,最后的wrong doing 怎么一直有,怎么才可以在正常读文件 的最后不运行那一个语句:

public class ComIfo {
    public void readTxt(String filePath) {
          
          try {
            File file = new File(filePath);
            if(file.isFile() && file.exists()) {
              InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
              BufferedReader br = new BufferedReader(isr);
              String[] lineTxt = null;
              
              while ((lineTxt = br.readLine().split(",")) != null) {
                System.out.println(lineTxt[1]);
              }
              br.close();
            } else {
              System.out.println(" no such file");
            }
          } catch (Exception e) {
            System.out.println("wrong doing");
          }
          
          }
    }

catch块本就不必执行,除非对应的try块中发生异常。
你的代码正因为出现了java.lang.NullPointerException,才输出了不该输出的内容。
如果不信的话,你可以在catch块加一行:e.printStackTrace();

我试着帮你改一下代码,你可以试着运行一下:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class ComIfo {
    public void readTxt(String filePath) {
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                while (true) {
                    String lineText = br.readLine();
                    if (lineText != null) {
                        String[] lineTextArray = lineText.split(",");
                        System.out.println(lineTextArray[0]);
                    } else {
                        break;
                    }
                }
                br.close();
            } else {
                System.out.println("no such file");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("wrong doing");
        }
    }
}

如果我的回答对你有帮助,希望你能采纳!