我是一个 java 菜鸟,也是这个网站的新手,所以请在这里多多包涵。如果我在发布此内容时做错了什么,请告诉我,对于我所做的任何事情或任何错误的语法,我提前道歉。
我需要在 java 中编写一个自定义 CSV 解析器,它不会在引号内分隔逗号。我不能使用任何与 CSV 类相关的东西。1,2,3,4 -> 1 2 3 4 a,"b,c",d -> ab,cd
无论我尝试什么,我总是会遇到异常
import java.io.*;
import java.util.*;
public class csv
{
public static void main(String[] args)
{
File file = new File("csv.test");
BufferedReader buf = null;
try
{
buf = new BufferedReader(new FileReader(file));
String str;
while ((str = buf.readLine()) != null)
{
String[] values = null; // array for saving each split substr
int c1 = 0; // counter for current position in string
int c2 = 0; // counter for next space in array to save substr
int c3 = 0; // location of last comma or quotation for substring creation
int i = 0; // counter used later for printing
while (c1 <= str.length())
{
char x = str.charAt(c1);
String s = Character.toString(x);
if (c1 == str.length())
{
values[c2] = str.substring(c3, (c1 - 1));
}
else if (s == ",")
{
values[c2] = str.substring(c3, (c1 - 1));
c1++;
c2++;
c3++;
}
else if (s == "\"")
{
c1++;
c3 = c1;
while (s != "\"")
c1++;
values[c2] = str.substring(c3, (c1 - 1));
c1 = c1 + 2;
c2++;
c3 = c1;
}
else
{
c1++;
}
while (i < values.length)
System.out.println("\"" + values[i] + "\"");
}
}
}
catch (Exception e)
{
System.out.println("Error locating test file");
}
}
}
我尝试删除所有逻辑并测试它是否与文件 io 相关。读起来很好,所以我归结为它与逻辑有关。我看了一遍,找不到任何问题。我什至让一个朋友看过它,说它看起来不错。异常在哪里抛出?