我是一个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");
}
}
}
我已经尝试排除所有逻辑问题并测试它是否与文件输入输出相关。读取方面都没问题,所以现在我认为是逻辑问题。我仔细检查了代码,但没有找到任何问题。我甚至让我的朋友帮我看过,他也说代码没有问题。异常是在哪里抛出的?
catch
块中添加e.printStackTrace();
并告诉我们它的输出内容。 - Stephen C