【问题标题】:CSV writing data beside each otherCSV 将数据并排写入
【发布时间】:2017-05-22 16:56:25
【问题描述】:

我正在将 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 下方。 同样对于设备 C,我想把它写在设备 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() 方法调用。

我怎样才能在旁边实现写作?

【问题讨论】:

    标签: java android csv


    【解决方案1】:

    在写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
    

    【讨论】:

    • 还是不行……还是一样
    • 好的 刚刚做了最后一次编辑。代码测试和验证,对我有用。
    • 还是同样的问题...我得到的输出是 - DeviceA -85 DS:DA:AB:2B:B4:AE DecviceB -90
    • 已更新以向您展示我的测试用例。如果它不起作用,则说明您的代码有其他问题。
    • 另外,为什么没有逗号?这是一个 CSV 文件。
    猜你喜欢
    • 2015-08-15
    • 2017-12-03
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 2018-11-29
    • 2023-02-21
    • 1970-01-01
    相关资源
    最近更新 更多