如何使用Java扫描仪识别回车 [英] How to recognize carriage return using java scanner

查看:87
本文介绍了如何使用Java扫描仪识别回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将CS​​V文件读取到我的应用程序中,以将一堆数据读取到表中. 每行用逗号分隔,并且行的每一端都有回车符.我尝试在Java中使用扫描仪读取定界符设置为(,")的第一行,但是当它到达回车符时,我无法弄清楚如何在第一行的末尾停止扫描仪.这是我到目前为止可以扫描文件中所有内容的代码,因为它不会在回车时停止.

I am trying to read a CSV file in to my application to read a bunch of data into a table. Every row is separated by commas and each end of the row has a carriage return. I try using the scanner in java to read the first line with delimiter set to (","), but I can't figure out how to stop the scanner at the end of the first row when it reached the carriage return. This is the code I have so far that scans in everything in the file since it doesn't stop at carriage returns.

Scanner scn = new Scanner(inputStream);

                    Vector<String> columnTitles = new Vector<String>();
                    scn.useDelimiter(",");

                    // Read the first line to get the column names.
                    while(!scn.hasNextInt())
                    {
                        String newStr = scn.next();
                        columnTitles.add(newStr);
                        System.out.print(newStr);
                    }

这个主意似乎很简单,但是在我看来,到处都是无用的例子,所有的例子都不起作用.

The idea seems so simple, yet everywhere I look has useless examples that all don't work.

推荐答案

如果您只是尝试用文件的第一行填充columnTitles向量,然后处理文件的其余部分(或不进行处理)

If you're simply trying to populate the columnTitles vector with the first line of the file and then process the rest of the file (or not)

  1. 在文件上使用BufferedReader将第一行读入字符串
  2. 使用该字符串创建扫描仪
  3. 使用第2步中的扫描仪填充矢量
  4. 然后,如果要处理文件的其余部分,请执行上述操作,但在while循环之前调用scn.nextLine()以跳过文件的第一行

这篇关于如何使用Java扫描仪识别回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆