Search code examples
androidopencsv

How to Read and Write to a csv file in Android?


I want to store 8 integers into a .csv file(the filename will be taken as an input from a EditText) and retrieve them when I want to.


Solution

  • To get the filename you can use this:

    EditText fileNameEdit= (EditText) getActivity().findViewById(R.id.fileName);
    String fileName = fileNameEdit.getText().toString();
    

    Then write the file on disk:

    try {
        String content = "Separe here integers by semi-colon";
        File file = new File(fileName +".csv");
        // if file doesnt exists, then create it
        if (!file.exists()) {
           file.createNewFile();
        }
    
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    To read the file:

    BufferedReader br = null; 
    try {
      String sCurrentLine;
      br = new BufferedReader(new FileReader(fileName+".csv"));
      while ((sCurrentLine = br.readLine()) != null) {
        System.out.println(sCurrentLine);
      }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
      try {
         if (br != null)br.close();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
    }
    

    Then to have the Integers you can use split function:

    String[] intArray = sCurrentLine.split(";");