簡體   English   中英

如何讀取 CSV 文件?

[英]How to read a CSV file?

我正在創建一個應用程序,我在其中進行一些實時圖像分析並將它們存儲到一個 csv 文件中。 csv 有 2 列時間和每幀的 y 值。

我想讀取這個文件並將 2 列中的值存儲到雙數組中。 我想要這個是因為我想對數據執行快速傅立葉變換。

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類獲取每一幀的數據。 之后,我將這些值存儲到一個名為temp.csv的 CSV 文件中。

問題

  1. 我想讀取這個 csv 並將第一列(時間)存儲到一個雙數組中,將第二列(yAverage)存儲到另一個雙數組中。
  2. 一旦我將所有數據存儲到雙數組中,我也想刪除該文件。

我怎樣才能做到這一點?

我建議你使用像 OpenCSV 這樣的開源庫來從 CSV 文件中獲取數據。 當您實現庫時,只需遍歷 x 和 y 列並將它們分配給數組。 使用 OpenCSV,它看起來像那樣。 但是,如果具有相同索引坐標的 x 和 y 彼此相關,我也會建議您采用更面向對象的方法。

    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();
    }

從盧卡斯給出的答案中,我得到了解決方案的方向

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 存儲庫中找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM