【发布时间】:2015-05-14 22:49:11
【问题描述】:
我是 Java 新手,现在了解基本知识。我有一个 csv 文件,其中的行都是以下结构:
Int,,text,text,Int,text,text,text,,text,text,,text,text,,,text,,text,,,Int,Int
当我看到那个 csv 文件时,我很困惑,因为它是由单逗号、双逗号和三逗号分隔的。有时,特定的文本或 int 也是空的,excel 无法再以正确的方式显示 csv。
所以我想我使用 Java 编写一个程序来使列仅用一个逗号分隔。然后将结果保存在一个新的 csv 文件中。 (我还没有实现如何将它写入另一个文件)通过一些研究,我设法编写了一个文件阅读器来读取 csv 文件,但就是这样。我怎样才能达到我想要的结果?
到目前为止我做了什么:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
class Read {
public static void main(String[] args) {
FileReader myFile = null;
BufferedReader buff = null;
final ArrayList<String> lines = new ArrayList<String>();
try {
myFile = new FileReader("thisisthepathofthecsvsource");
buff = new BufferedReader(myFile);
String line;
while ((line = buff.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
System.err.println("Error2 :" + e);
} finally {
try {
buff.close();
myFile.close();
} catch (IOException e) {
System.err.println("Error2 :" + e);
}
}
final String[][] valuesArray = new String[lines.size()][];
int cnt = 0;
for (final String line : lines) {
valuesArray[cnt++] = line.split(",");
}
for (String[] arr : valuesArray) {
System.out.println(Arrays.toString(arr));
}
}
}
【问题讨论】:
-
您要删除空白字段吗?至于写回您的数据,请查看 PrintWriter 或此 SO 线程 stackoverflow.com/questions/2885173/…
-
好的,非常感谢您的回答。现在我的行只用一个逗号分隔。到目前为止还不错。但是现在我想将字符“-”填充到空的列中。实际上,我希望这些行与所有其他行的结构相同,以便我可以轻松地将其导入到 excel 中,并使用过滤器对其进行过滤。很抱歉,这听起来很简单,但我花了这么长时间,因为我是 java 新手 :(。我一直在努力!
-
您的示例 csv 行表明该行有 23 列,其中一些列是空的(即双逗号或三逗号)。所有的 csv 行都是这样的吗,它们有 23 列?