有 Java 编程相关的问题?

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

java如何使用Scanner类和分隔符忽略以//开头的整行文本

我试图从.txt文件中读取数据,我需要忽略以//或空行开头的任何行,但我似乎无法使分隔符正常工作

public void readVehicleData()
throws FileNotFoundException
{
    FileDialog fileBox = new FileDialog(myFrame, "Open", FileDialog.LOAD);
    fileBox.setVisible(true);

    String filename = fileBox.getFile();
    File vehicleData = new File(filename);

    Scanner scanner = new Scanner(vehicleData).useDelimiter("\"(,\")?");


    while( scanner.hasNext() )
    {
        String lineOfText = scanner.nextLine();

        System.out.println(lineOfText);

    }
    scanner.close();
}

这是最新的。我正在尝试读取的txt文件:

// this is a comment, any lines that start with //
// (and blank lines) should be ignored

AA, TF-63403, MJ09TFE, Fiat 
A, TF-61273, MJ09TFD, Fiat
A, TF-64810, NR59GHD, Ford
B , TF-68670,MA59DCS, Vauxhall
B, TF-61854,  MJ09TFG, Fiat
B, TF-69215, PT09TAW, Peugeot
C, TF-67358, NR59GHM, Ford

共 (1) 个答案

  1. # 1 楼答案

    如果我正确理解了您的问题,您不需要指定分隔符

    Scanner scanner = new Scanner(vehicleData);
    
    
    while( scanner.hasNext() )
    {
        String lineOfText = scanner.nextLine();
        if(lineOfText.length() == 0 || lineOfText.startsWith("//"))
                continue;
        System.out.println(lineOfText);
    
    }
    scanner.close();