我是一个 Java 菜鸟,也是这个网站的新手,所以请多多包涵。如果我在发帖时做错了什么,请告诉我,对于我碰巧做的任何事情或任何错误的语法,我提前道歉。
我需要在 java 中编写一个自定义 CSV 解析器,它不会在引号内分隔逗号。我不能使用与 CSV 类相关的任何内容。 1,2,3,4 -> 1 2 3 4 a,"b,c",d -> a b,c d
无论我尝试什么,我总是得到一个异常
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 相关。读起来很好,所以我认为它与逻辑相关。我仔细看了看,找不到任何问题。我什至让一个 friend 看了一遍,说看起来不错。异常在哪里抛出?
最佳答案
你没有在这一行 String[] values = null;
中初始化你的 values
因此当你使用它时它会失败,即在列表 values[c2 ] = str.substring(c3, (c1 - 1));
.
要解决此问题,请使用适当的长度初始化 values
数组,例如String[] values = new String[SIZE];
。可能您需要使用 str.length()
作为数组的 SIZE
。
同样在您的比较 else if (s == ",")
中,您正在使用 ==
比较 String,这是不正确的。相反,您可以将 x
本身用作 else if (x == ',')
。
编辑:您的以下条件将使c1
无限递增,因为您没有更改str(按照建议更正后的x)
任何地方。
旧情况:
while (s != "\"")
c1++;
按照建议更改后(仍然错误,因为 x 在 while 循环中没有更改):
while (x != '"')
c1++;
请更正循环逻辑。
关于java - 我找不到导致异常的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13447123/