简体   繁体   English

从byte []写csv文件

[英]Write csv file from byte[]

I am getting a file in byte[] which have comma separated values in quotes, I want to save it as CSV by using OpenCSV. 我在byte[]获取了一个用逗号分隔引号值的文件,我希望使用OpenCSV将其保存为CSV。 I am using this to save it in CSV format. 用它来保存为CSV格式。

Following is my code to convert byte[] to array and then store it in file 以下是我将code []转换为数组然后将其存储在文件中的代码

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();

But this above code puts extra quotes around and also merge all lines in one line. 但是上面的代码会在一行中添加额外的引号并将所有行合并在一起。

Any help on how to do this properly ? 有关如何正确执行此操作的任何帮助?

You can prevent adding quotes to the cell values within the constructor of CSVWriter , for example: 您可以阻止在CSVWriter的构造函数中为单元格值添加引号,例如:

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

Regarding the whole byte array persisted as a single row. 关于整个字节数组保持为单行。 Are you sure there are newlines within the original file. 您确定原始文件中有换行符吗?

If so you might get away by doing the following: 如果是这样,您可以通过执行以下操作来逃避:

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

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

Got this from splitting a byte array on a particular byte 通过在特定字节上拆分字节数组得到这个

I think Apache Commons CSV is a better CSV library. 我认为Apache Commons CSV是一个更好的CSV库。 From the pasted code it is not clear if you want to somehow change the contents of the file or just duplicate it: in the latter case you don't even need to parse the file as CSV records - just copy it byte-for-byte. 从粘贴的代码中不清楚是否要以某种方式更改文件的内容或只是复制它:在后一种情况下,您甚至不需要将文件解析为CSV记录 - 只需逐字节复制它。 In the former case, ie if you need to modify the content of the file, you need something like (Commons CSV used here) 在前一种情况下,即如果您需要修改文件的内容,则需要类似(此处使用的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();

Look at the Javadoc for CSVFormat 查看CSVFormat的Javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM