如何将一系列传入值写入 java 中的 csv

How to write a series of incoming values to csv in java

我有一个生成 3 个值的代码 x,y,z
x,y,z每时每刻都在更新
我需要将这些值写入 java 中的 csv 文件。 帮帮我

start.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String tempX = String.valueOf(lastX);
                String tempY = String.valueOf(lastY);
                String tempZ = String.valueOf(lastZ);
                // System.out.println("x value: " + temp);
                CSVWriter csv = null;
                try {
                    csv = new CSVWriter(new FileWriter("/sdcard/myfile.csv"), ',');
                    //List<String> lists = new ArrayList<String>();
                    String[] values = new String[]{tempX,tempY,tempZ,"1"};

                        csv.writeNext(values);

                    csv.close();
                    Toast.makeText(getApplicationContext(), "Able to write CSV", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "Unable to write CSV", Toast.LENGTH_LONG).show();
                }
            }

使用 FileWrite 将 x,y,z 写入 csv 文件。 请阅读此代码示例。这是不言自明的。

    import java.io.FileWriter;
    import java.io.IOException;

    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\n";
    private static final String FILE_HEADER = "x,y,z";

    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter(fileName);
        fileWriter.append(FILE_HEADER.toString());
        fileWriter.append(NEW_LINE_SEPARATOR);
        // Write x, y, z
        fileWriter.append(x);
        fileWriter.append(y);
        fileWriter.append(z);
        System.out.println("CSV file was created successfully !!!");
    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
        e.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter !!!");
            e.printStackTrace();
        }

    }

http://examples.javacodegeeks.com/core-java/writeread-csv-files-in-java-example/

您可以按如下方式传递整个数组,而不是遍历 String[] 数组的条目并将其写入 CSV:

/* 
 * bellow will insert values array values.length times, 
 */
for(int i=0;i<values.length;i++){
    csv.writeNext(values);
}

将上面替换为下面,将数组的所有条目写入 CSV

csv.writeNext(values); 

我使用 OpenCSV 提出了以下解决方案。出于测试目的,我添加了一个循环以将值插入 CSV,让您了解如何更新 CSV。

import java.io.FileWriter;
import java.io.IOException;

import com.opencsv.CSVWriter;

public class OpenCSVTest {

    public static void main(String[] args) {
        CSVProcessor process = new CSVProcessor(); 

        String[] entries = new String[]{"1","2","3","x"}; 

        //assume each loop is when you get updated entries
        for(int i = 0; i < 5; i++) {
            //store to the file 
            process.storeUpdatedValues(entries);

            //change the vaues to simulate update in x,y,z
            entries[0] = entries[0] + 5; 
            entries[1] = entries[1] + 10; 
            entries[2] = entries[2] + 3; 
            entries[3] = entries[3] + "i:" + i; 
        }
    }
}

class CSVProcessor {
    public void storeUpdatedValues(String[] entries) {
        CSVWriter writer;
        try {
             /*
              *  First arg to CSVWriter is FileWriter that references your file in the disk
              *  Second arg to the CSVWriter is the delimiter, can be comma, tab, etc. 
              *  First arg to FileWriter is location of your file to write to 
              *  Second arg to FileWriter is a flag stating that if file found then append to it 
              */
             writer = new CSVWriter(new FileWriter("C:\test_java\yourfile.csv", true), ',');

            // feed in your array - you don't need to loop through the items of array
             writer.writeNext(entries);

             // close the writer.
             writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

当你 运行 一次程序时,你会得到以下输出(5 行,因为循环是 运行 五次):

1          2             3           x
15         210           33          xi:0
155        21010         333         xi:0i:1
1555       2101010       3333        xi:0i:1i:2
15555      210101010     33333       xi:0i:1i:2i:3

使用 CSVProcessor 的步骤 class:

  1. 实例化并创建一个对象
  2. 每当 x、y、z 的值更新时,将它们传递给 CSVProcessor 的实例
  3. 每当 x,y,z 更新时重复第 2 行。您的更新将附加到 CSV 文件中。