2017-10-14 6 views
-1

저는 실시간 이미지 분석을하고 csv 파일에 저장하는 어플리케이션을 만들고 있습니다. CSV는 각 프레임의 2 열의 시간 및 y 값을가집니다.CSV 파일을 읽는 방법?

이 파일을 읽고 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 클래스에서 데이터를 가져 오는 것입니다. 그 다음에 값을 temporary.csv이라는 CSV 파일에 저장합니다.

문제

  1. I이 CSV를 읽고 대 배열 및 다른 배열로 두 번째 열 (yAverage)로 첫 번째 열 (시간)를 저장할.
  2. 또한 모든 데이터가 double 배열에 저장되면 파일을 삭제하고 싶습니다.

어떻게하면됩니까?

+0

여기서 CSV 파일은 자산 또는 서버 –

+0

에 저장 되었습니까? 내 외부로 저장됩니다. 내 장치의 저장. 'storeCsv' 메쏘드를 보면'bpReader'라는 폴더를 외부 저장소에 저장 한 것을 볼 수 있습니다. – Mill3r

+0

여기에 [안드로이드에서 csv 파일을 읽는 방법] (https://inducesmile.com/android-tips/android-how-to-read-csv-file-from-remote-server-or-assets)의 좋은 예입니다. -folder-in-android /) 당신이보기에 도움이 될 수도 있습니다 –

답변

1

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

저장된 csv 파일의 경로를 기록했는데'/ storage/emulated/0/bpReader/temporary.csv'라는 것을 알았습니다. 따라서'csvFile'에 대해이 경로를 지정했습니다. 'reader = new CSVReader (new FileReader (csvFile));에'java.lang.NoClassDefFoundError : 실패한 해결 : Lorg/apache/commons/lang3/ObjectUtils; '오류가 나타납니다. 나는 여전히 내 파일의 경로를 지정하는 방법과 혼동 스럽다. – Mill3r

+0

문제를 해결했습니다.'https : // mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.6'을 그라데이션에 추가해야했습니다. 파일 경로를 'String getPath = Environment로 설정하십시오.getExternalStorageDirectory() + "/ bpReader"; 문자열 csvFile = "temporary.csv"; 문자열 경로 = getPath + "/"+ csvFile; – Mill3r

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

을로 방향을 가지고 그리고 내가 찾을 수 있습니다 내 Gradle을 ,,에

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

를 추가했다 MVN repository

관련 문제