CSV将数据写在彼此旁边

时间:2017-05-22 16:56:26

标签: java android csv

我正在写入BLE扫描结果的CSV文件。我目前正在做的是将所有数据写在另一个下面。 数据包括设备名称,rssi和mac地址。例如,CSV文件如下所示 -

DeviceA -85 DS:DA:AB:2B:B4:AE
DeviceB -100 2C:18:0B:2B:96:9E
DeviceA -85 DS:DA:AB:2B:B4:AE

我的要求就是这样写 -

DeviceA -85 DS:DA:AB:2B:B4:AE DeviceB -100 2C:18:0B:2B:96:9E
DeviceA -85 DS:DA:AB:2B:B4:AE

在设备A的最后一列之后,我需要从设备B的新列开始,而不是在设备A下面写。 同样对于Device C,我想在Device C旁边写它......依此类推。这是我写入CSV的代码。

public final String DATA_SEPARATOR = ",";
    public final String LINE_SEPARATOR = System
            .getProperty("line.separator");

          try {

                fileName = "test.csv";


               path = Environment.getExternalStorageDirectory()
                            + File.separator + "Documents";


                path += File.separatorChar + "SampleApp";
                File file = new File(path, fileName);

                new File(path).mkdirs();
                file.createNewFile();

                fileStream = new OutputStreamWriter(new FileOutputStream(file));

                fileStream.write("sep= " + DATA_SEPARATOR + LINE_SEPARATOR);
            } catch (IOException e) {
                e.printStackTrace();
                fileStream = null;
            }

 private void writeElements(Object... elements) throws IOException {


            if (fileStream != null) {
                for (Object o : elements) {
                    fileStream.write(o.toString());
                    fileStream.write(DATA_SEPARATOR);
                }
                fileStream.write(LINE_SEPARATOR);
            }

 }

writeElements(btDeviceName, btRSSIValue, btMacId)时不时从bluetoothScan()方法调用。

如何在旁边写作?

1 个答案:

答案 0 :(得分:0)

在写LINE_SEPARATOR之前,只需将2放在同一行。将writeElements中的内容更改为以下内容:

private void writeElements(Object... elements) throws IOException {
    if (fileStream != null) {
        for (int index = 1; index < elements.length + 1; index++) {
            String address = elements[index - 1].toString();
            fileStream.write(address);
            if(index % 2 == 0) fileStream.write(LINE_SEPARATOR);
            else fileStream.write(DATA_SEPARATOR);
        }
    }
}

测试:

Object[] elements = new Object[4];
elements[0] = "here";
elements[1] = "are";
elements[2] = "some";
elements[3] = "words";

writeElements(elements);

打开文件时:

here,are
some,words
相关问题