如何读取CSV文件?

时间:2017-10-14 09:47:53

标签: android arrays csv

我正在创建一个应用程序,我可以在其中进行实时图像分析并将它们存储到csv文件中。 csv具有2列时间和每帧的y值。

我想读取此文件并将2列中的值存储到double数组中。我想要这个,因为我想对数据进行快速傅里叶变换。

public class MainActivity extends AppCompatActivity implements CameraView.PreviewReadyCallback {
private static Camera camera = null;
private CameraView image = null;

private LineChart bp_graph;
private int img_Y_Avg, img_U_Avg, img_V_Avg;
private long end = 0, begin = 0;
double valueY, valueU, valueV;
Handler handler;
private int readingRemaining = 1200;
private static long time1, time2, timeDifference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    bp_graph = (LineChart)findViewById(R.id.graph);


    graph_features();

    //open camera
    try {
        camera = Camera.open();

        handler = new Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                camera.stopPreview();
                camera.release();
            }
        };
        handler.postDelayed(runnable, 30000);

    } catch (Exception e) {
        Log.d("ERROR", "Failed to get camera: " + e.getMessage());
    }

    if (camera != null) {
        image = new CameraView(this, camera);
        FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
        camera_view.addView(image);
        image.setOnPreviewReady(this);
    }


}


@Override
protected void onResume(){
    super.onResume();
}

@Override
protected void onPause() {
    super.onPause();
}


@Override
public void onPreviewFrame(long startTime, int ySum, int uSum, int vSum, long endTime) {
    begin = startTime;
    img_Y_Avg = ySum;
    img_U_Avg = uSum;
    img_V_Avg = vSum;
    end = endTime;

   showResults(begin, img_Y_Avg, img_U_Avg, img_V_Avg, end);


}

private void showResults(long startTime, int ySum, int uSum, int vSum, long endTime){

    //set value of Y on the text view
    TextView valueOfY = (TextView)findViewById(R.id.valueY);
    //valueY = img_Y_Avg;
    valueOfY.setText(String.valueOf(img_Y_Avg));

    //start time in milliseconds
    long StartDurationInMs = TimeUnit.MILLISECONDS.convert(begin, TimeUnit.MILLISECONDS);
    ArrayList<Long> startOfTime = new ArrayList<>();
    startOfTime.add(StartDurationInMs);

    //store value to array list
    ArrayList<Integer> yAverage = new ArrayList<>();
    yAverage.add(img_Y_Avg);

    //convert to readable format
    String readableDate = new SimpleDateFormat("MMM dd,yyyy, HH:mm:ss.SSS").format(EndDurationInMs);
    Log.d("Date ", readableDate);


    Log.d("time ", String.valueOf(String.valueOf(yAverage.size())));
    //store when all array are generated
    Log.d("time ", String.valueOf(StartDurationInMs));


    ArrayList<Long> getValues = new ArrayList<>();

    for(int i = 0; i < yAverage.size(); i++) {
        getValues.add(startOfTime.get(i));
        getValues.add((long)(yAverage.get(i)));
    }

    //store the yAverage and start time to csv file
    storeCsv(yAverage, getValues);


    Log.d("MyEntryData", String.valueOf(getValues));

}

public void storeCsv(ArrayList<Integer>yAverage, ArrayList<Long>getValues){

    String filename = "temporary.csv";

    //File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/bpReader";
    //File logDir = new File (directoryDownload, "bpReader"); //Creates a new folder in DOWNLOAD directory
    File logDir = new File(path);
    logDir.mkdirs();
    File file = new File(logDir, filename);


    FileOutputStream outputStream = null;
       try {
           file.createNewFile();
           outputStream = new FileOutputStream(file, true);
           //outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
           for (int i = 0; i < yAverage.size(); i += 2) {
               outputStream.write((getValues.get(i) + ",").getBytes());
               outputStream.write((getValues.get(i + 1) + "\n").getBytes());
               //outputStream.write((getValues.get(i + 2) + ",").getBytes());
               //outputStream.write((getValues.get(i + 3) + "\n").getBytes());
           }
           outputStream.flush();
           outputStream.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
}

public void readCsv(){

}
}

这是我的 MainActivity 。我在这里做的是借助我创建的界面从每个帧的 CameraView 类获取数据。之后,我将值存储到名为 temporary.csv 的CSV文件中。

问题

  1. 我想读取这个csv并将第一列(时间)存储到一个双数组中,将第二列(yAverage)存储到另一个double数组中。
  2. 一旦我将所有数据存储到双数组中,我也想删除该文件。
  3. 我该怎么做?

2 个答案:

答案 0 :(得分:1)

我建议您使用OpenCSV等开源库从CSV文件中获取数据。当您实现库时,只需迭代x和y列并将它们分配给数组即可。使用OpenCSV,它看起来就像那样。但是如果具有相同索引坐标的x和y彼此相关,我还建议你使用更多对象orientec方法。

    String csvFile = "/Users/mkyong/csv/country3.csv";
    int length = 100; //If you dont know how many entries the csv file has i would suggest to use ArrayList
    double[] xCoords = new double[length];
    double[] yCoords = new double[length];


    CSVReader reader = null;
    try {
        reader = new CSVReader(new FileReader(csvFile));
        String[] line;
        int i = 0;
        while ((line = reader.readNext()) != null) {
            xCoords[i] = Double.parseDouble(line[0]);
            yCoords[i] = Double.parseDouble(line[1]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

从卢卡斯的回答中,我得到了解决方案的方向

public void readCsv(){
    //set the path to the file
    String getPath = Environment.getExternalStorageDirectory() + "/bpReader";
    String csvFile = "temporary.csv";
    String path = getPath+ "/" + csvFile;


    //File file = new File(path, csvFile);
    int length = 500;
    double[] xCoords = new double[length];
    double[] yCoords = new double[length];


    CSVReader reader = null;
    try {
        File myFile = new File (path);
        reader = new CSVReader(new FileReader(myFile));
        String[] line;
        int i = 0;
        while ((line = reader.readNext()) != null) {
            xCoords[i] = Double.parseDouble(line[0]) ;
            yCoords[i] = Double.parseDouble(line[1]);
            Log.d("read:: ", "Time: "+String.valueOf(xCoords[i])+" Y: "+String.valueOf(yCoords[i]));
        }

        myFile.delete();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

然后我不得不添加

// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.6'

到我的gradle ,,可以在MVN repository

找到