如何使用带有多个逗号和双引号的scanner在java中读取.csv文件
我有一个.csv文件,它有逗号和双引号分隔的值 现在我想解析逗号分隔的值,当双引号中有值时,我希望scanner使用双引号作为分隔符 要分析的示例行: 123,学生,“考试通知”,“模式应相同、有效、正确” 现在我想像这样解析它:如何使用带有多个逗号和双引号的scanner在java中读取.csv文件,java,design-patterns,java.util.scanner,Java,Design Patterns,Java.util.scanner,我有一个.csv文件,它有逗号和双引号分隔的值 现在我想解析逗号分隔的值,当双引号中有值时,我希望scanner使用双引号作为分隔符 要分析的示例行: 123,学生,“考试通知”,“模式应相同、有效、正确” 现在我想像这样解析它: 123 //comma seperated student exam notification //when "" it should be double quote separated pattern should be same,validated,prop
123 //comma seperated
student
exam notification //when "" it should be double quote separated
pattern should be same,validated,proper //ignore , comma in double quotes
我尝试过的代码:
scanner.useDelimiter(",|\"");
因此,它可以同时使用和“”,但在这两者之间,它会打印空白行,,“,并且不能忽略双引号之间的逗号
你知道如何分类吗?不要重新发明轮子…在这里试试超级CVS 关于使用CSV解析器可以自动处理引用元素中的逗号、跨多行的值等。您也可以使用该库将文本序列化回CSV
CSVReader reader = new CSVReader(new FileReader("file.csv"));
String [] nextLine;
// prints the following for the line in your question
while ((nextLine = reader.readNext()) != null) {
System.out.println(nextLine[0]); // 123
System.out.println(nextLine[1]); // student
System.out.println(nextLine[2]); // exam notification
System.out.println(nextLine[3]); // pattern should be same,validated,proper
}
有几种方法可以实现你想做的事情 1.)使用支持解析CSV的现有库,如Ravi Thapliyal和Oibaf 2.)您可以提供您的方法
a). if every line in your CSV have a uniform format like :
line 1 : 123,student,"exam notif","word , word , word"
line 2 : 45345,not student,"no exam notif","word,word,word"
you can say like
while(scan.hasNextLine()){
String line = scan.nextLine();
//split it using double quotes first
temp = line.split("\"");
//then just remove commas outside the double quoted objects
for(int x = 0; x<temp.length; x++){
if(temp[x].startsWith(",")) {temp[x] = temp[x].substring(1,temp[x].length()); }
if(temp[x].endsWith(",")) {temp[x] = temp[x].substring(0,temp[x].length()-1); }
}
a)。如果CSV中的每一行都有统一的格式,如:
第1行:123,学生,“考试通知”,“单词,单词,单词”
第2行:45345,不是学生,“不考试不如果”,“字,字,字”
你可以说喜欢
while(scan.hasNextLine()){
String line=scan.nextLine();
//首先使用双引号将其拆分
温度=行分割(“\”);
//然后删除双引号对象外的逗号
对于(int x=0;席)想要编辑CVS到CSV。但是编辑仅在超过6个字符改变时才允许。