【发布时间】:2017-04-16 14:28:40
【问题描述】:
我的应用程序的一部分通过以下方式将数据写入 .csv 文件:
public class ExampleWriter {
public static final int COUNT = 10_000;
public static final String FILE = "test.csv";
public static void main(String[] args) throws Exception {
try (OutputStream os = new FileOutputStream(FILE)){
os.write(239);
os.write(187);
os.write(191);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
for (int i = 0; i < COUNT; i++) {
writer.write(Integer.toString(i));
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(checkLineCount(COUNT, new File(FILE)));
}
public static String checkLineCount(int expectedLineCount, File file) throws Exception {
BufferedReader expectedReader = new BufferedReader(new FileReader(file));
try {
int lineCount = 0;
while (expectedReader.readLine() != null) {
lineCount++;
}
if (expectedLineCount == lineCount) {
return "correct";
} else {
return "incorrect";
}
}
finally {
expectedReader.close();
}
}
}
文件将在 excel 中打开,并且所有类型的语言都存在于数据中。 os.write 部分用于在文件前加上字节顺序标记,以启用各种字符。
不知何故,文件中的行数与循环中的计数不匹配,我无法弄清楚如何。对于我在这里做错的任何帮助将不胜感激。
【问题讨论】:
标签: java csv bufferedwriter byte-order-mark