【问题标题】:Write csv file from byte[]从 byte[] 写入 csv 文件
【发布时间】:2016-09-29 03:41:59
【问题描述】:

我在 byte[] 中得到一个文件,该文件在引号中有逗号分隔值,我想使用 OpenCSV 将其保存为 CSV。我是using this 以CSV格式保存。

以下是我将 byte[] 转换为数组然后将其存储在文件中的代码

byte[] bytes = myByteStream.getFile();

String decoded = new String(bytes, "UTF-8");            
//String lines[] = decoded.split("\\r?\\n");


FileOutputStream fos = new FileOutputStream("/home/myPC/Desktop/test.csv"); 
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
CSVWriter writer = new CSVWriter(osw);
String[] row = {decoded};

writer.writeNext(row);
writer.close();
osw.close();

但是上面的代码在周围添加了额外的引号,并且还将所有行合并为一行。

关于如何正确执行此操作的任何帮助?

【问题讨论】:

  • 字节数组中的行是否被换行符分割?

标签: java bytearray opencsv


【解决方案1】:

您可以防止在CSVWriter的构造函数中为单元格值添加引号,例如:

CSVWriter writer = new CSVWriter(osw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

关于整个字节数组持久化为一行。您确定原始文件中有换行符吗?

如果是这样,您可以通过以下方式逃脱:

    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "ASCII"));

String line;
while ((line = reader.readLine()) != null) {
    // Handle the line, ideally in a separate method
}

splitting a byte array on a particular byte得到这个

【讨论】:

    【解决方案2】:

    我认为Apache Commons CSV 是一个更好的 CSV 库。从粘贴的代码中不清楚您是想以某种方式更改文件的内容还是只是复制它:在后一种情况下,您甚至不需要将文件解析为 CSV 记录 - 只需逐个字节地复制它.在前一种情况下,即如果你需要修改文件的内容,你需要类似(这里使用的Commons CSV)

    CSVParser parser = CSVFormat.newFormat(',').parse(
        new InputStreamReader(new ByteArrayInputStream(bytes), "UTF8"));
    CSVPrinter printer = CSVFormat.newFormat(',').print(out);
    for (CSVRecord record : parser) {
      try {
        printer.printRecord(record);
      } catch (Exception e) {
        throw new RuntimeException("Error at line "
          + parser.getCurrentLineNumber(), e);
      }
    }
    parser.close();
    printer.close();
    

    查看CSVFormat的Javadoc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      相关资源
      最近更新 更多