【问题标题】:How to write a series of incoming values to csv in java如何在java中将一系列传入值写入csv
【发布时间】:2015-11-18 23:28:02
【问题描述】:

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

【问题讨论】:

  • 添加你已有的代码
  • 我的 x,y 和 z 就像不时更新一样,所以我需要将所有这些 x,y,z 值保存到 csv 文件中
  • 您面临的问题是什么?你想要什么样的帮助?您的 x 和 y 和 z 值会定期更新,这看起来不是问题。请明确说明您面临的问题是什么并且需要帮助?您添加的代码是否不起作用,如果是,错误是什么。如果帮助是其他方面的,那么请明确定义什么,以便我们为您提供相应的帮助。

标签: java arrays export-to-csv


【解决方案1】:

您可以按如下方式传递整个数组,而不是遍历 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。

【讨论】:

  • 嘿,我也使用了建议的,但它只将一组数组写入 csv,因为我需要为所有 xyz 值更新值。
  • 我需要运行一个循环来将所有更新的 xyz 写入 csv。请帮帮我
  • 您面临的问题是什么?有什么错误吗?
  • 我在 csv 中只得到一组值
  • 也发布代码的其他部分?我看不出 x,y,z 的值是如何变化的,无法说明为什么会发生这种情况。
【解决方案2】:

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

【讨论】:

  • 我正在使用 CSV Writer 来做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多