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

时间:2015-11-18 23:28:03

标签: java arrays export-to-csv

我有一个产生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();
                }
            }

2 个答案:

答案 0 :(得分:0)

使用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/

答案 1 :(得分:0)

不是循环遍历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行因为循环运行了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类的步骤:

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