有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用FileReader测试文件是否为空

我正在尝试向while循环中的代码块添加一个else if,在该循环下面测试LandingsData.txt文件是否为空。如果为空,则打印"Starting with an empty system"

    FileReader fr = null;

    try {
        fr = new FileReader("LandingsData.txt");
        
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
    }

Scanner myFile = new Scanner(fr);
String line;
myFile.useDelimiter(",|\\n");
while (myFile.hasNext()) {
    line = myFile.next();
    if (line.equals("sl")) {
        StrongLanding sl = new StrongLanding();
        sl.setLandingId(Integer.parseInt(myFile.next()));
        sl.setLandingDesc(myFile.next());
        sl.setNumLandings(Integer.parseInt(myFile.next()));
        sl.setCost(Double.parseDouble(myFile.next()));
        landings.add(sl);
    } else if (line.equals("ul")) {
        UltimateLanding ul = new UltimateLanding();
        ul.setLandingId(Integer.parseInt(myFile.next()));
        ul.setLandingDesc(myFile.next());
        ul.setNumLandings(Integer.parseInt(myFile.next()));
        ul.setCost(Double.parseDouble(myFile.next()));
        landings.add(ul);
    } else if (fr.length() == 0) {
        System.out.println("Starting with an empty system");
    }
}

我用fr.length()fr.count()尝试了几种不同的方法,但我似乎收到了错误The method length() is undefined for the type FileReader

我还尝试了while循环之外的几个不同的地方,因为我认为这可能是问题所在,但没有运气

短暂性脑缺血发作


共 (2) 个答案

  1. # 1 楼答案

    Scanner myFile = new Scanner(fr);
    String line;
    myFile.useDelimiter(",|\\n");
    if (!myFile.hasNext()){
        System.out.println("Starting with an empty system");
    } else {
        while (myFile.hasNext()) {
            line = myFile.next();
            if (line.equals("sl")) {
                // Do stuff
            } else if (line.equals("ul")) {
                // Do stuff
            }
        }
    }
    

    在读取文件之前调用hasNext()一次,查看文件是否为空

  2. # 2 楼答案

    您可以使用以下代码检查文件是否为空:

    File myFile = new file("file.txt");
    
    if(myFile.isEmpty())
    {
        System.out.println("Starting with an empty system");
    }
    

    使用File类而不是FileReader

    或者,如果需要使用FileReader,可以这样做:

    // Checking if the first line of the file is empty
    BufferedReader br = new BufferedReader(new FileReader("file.txt"));     
    if (br.readLine() == null) 
    {
        System.out.println("No errors, and file empty");
    }
    

    在开始while循环之前进行检查,将第一行与两个字符串进行比较,然后检查文件是否为空