简体   繁体   English

使用扫描仪从CSV读取Java扫描程序并忽略结束行

[英]Java scanner read from csv using delimeter and ignore endline

The code: 编码:

public static void main(String[] args) throws Exception{
    Scanner scn = new Scanner(new File ("kektura.csv"));
    int kezd = 0;
    List <String> indul = new ArrayList<>();
    List <String> veg = new ArrayList<>();
    List <Double> hossz = new ArrayList<>();
    List <Integer> emel = new ArrayList<>();
    List <Integer> lejt = new ArrayList<>();
    List <Boolean> pecset = new ArrayList<>();
    kezd=scn.nextInt(); 
    scn.nextLine();
    while(scn.hasNextLine())
    {
        scn.useDelimiter(";");
        indul.add(scn.next());           
        veg.add(scn.next());            
        hossz.add(scn.nextDouble());           
        emel.add(scn.nextInt());            
        lejt.add(scn.nextInt());            
        if(scn.next()=="n")
        {
            pecset.add(Boolean.TRUE);             
        }
        else
        {
            pecset.add(Boolean.FALSE);             
        }
        scn.nextLine();
    }
    for(Object x : pecset)
    {
        System.out.println(x);
    }
    scn.close();
}

And the file (It's a csv file, it has more lines, but they are the same pattern): 和文件(这是一个csv文件,它具有更多行,但是它们是相同的模式):

192
Sumeg, vasutallomas;Sumeg, buszpalyaudvar;1,208;16;6;n
Sumeg, buszpalyaudvar;Mogyorosi-domb, geologiai bemutatohely;1,512;24;8;n
Mogyorosi-domb, geologiai bemutatohely;Sumegi bazaltbanya vasutallomas;1,576;13;43;n
Sumegi bazaltbanya vasutallomas;Sarvaly erdeszhaz, pecsetelohely;2,101;69;18;i

I have a problem with reading this. 我在阅读本文时遇到了问题。 Read the first line, it's okay. 阅读第一行,没关系。 But the second line isn't good, because (i think) the delimeter reads until the ( ; ) character, but in the end of the line, there's not a ( ; ) . 但是第二行效果不好,因为(我认为)分界符会一直读到(;)字符,但是在行的末尾没有(;)。 The last line of the while, I wrote scn.nextLine to read the \\n character, but it doesn't work. 最后一行,我写了scn.nextLine来读取\\ n字符,但是它不起作用。 I know thats a possible way, to read the line, and split it, but it's a school project, and the teacher told us to find out another solution. 我知道这是一种可行的方法,可以阅读并拆分行,但这是一个学校项目,老师告诉我们要找到其他解决方案。 Is there a way, to solve this? 有办法解决吗?

As your teacher wants you to find another solution, I propose to use a BufferedReader to read the file in single lines. 由于您的老师希望您找到其他解决方案,因此我建议使用BufferedReader来单行读取文件。 For each line you can then use String#split() and finally convert the respective parts to the required type ( Integer#parseInt() etc). 然后,对于每一行,您可以使用String#split()并最终将各个部分转换为所需的类型( Integer#parseInt()等)。

However, as this is stated as a homework question, I will not provide a full example. 但是,由于这是家庭作业问题,因此我将不提供完整示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM