我想借助Java将文本文件转换为excel文件。示例数据如下,
12A8 3.10 0.82 0.10 06:08:57
12A8 3.07 0.82 0.14 06:08:58
12A8 3.08 0.83 0.12 06:08:59
5C12 1.92 0.66 0.47 06:08:59
12A8 3.09 0.84 0.13 06:09:00
5C12 1.95 0.66 0.50 06:09:01
12A8 3.03 0.85 0.25 06:09:01
12A8 2.98 0.84 0.31 06:09:03
12A8 2.94 0.86 0.39 06:09:03
5C12 2.03 0.70 0.56 06:09:04
12A8 2.91 0.86 0.44 06:09:04
5C12 2.05 0.70 0.57 06:09:04
12A8 3.06 0.86 0.23 06:09:05
12A8 3.00 0.86 0.31 06:09:07
12A8 2.96 0.86 0.38 06:09:08
12A8 2.93 0.79 0.41 06:09:08
12A8 3.07 0.81 0.21 06:09:09
5C12 2.07 0.69 0.60 06:09:10
很明显,每一列都用空格分隔。
答案 0 :(得分:0)
要将此文档转换为CSV文件,您只需要将所有空格替换为逗号。这是您可以做到的方式。
final File input = new File("com/aexp/file.txt");
List<String> output = new ArrayList<>();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(input));
String line;
while((line = reader.readLine()) != null){
output.add(line.replaceAll(" ", ","));
}
reader.close();
writer = new BufferedWriter(new FileWriter(new File("output.txt")));
for (String s : output) {
writer.write(s);
writer.newLine();
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}