Reading CSV File In Android App

前端 未结 6 1556
北恋
北恋 2020-12-08 16:14

I\'m working on a proof-of-concept app so that I can implement the feature in a larger app I\'m making. I\'m a bit new to Java and Android Dev but hopefully this shouldn\'t

6条回答
  •  一生所求
    2020-12-08 16:55

    Try OpenCSV - it will make your life easier.

    First, add this package to your gradle dependencies as follows

    implementation 'com.opencsv:opencsv:4.6'
    

    Then you can either do

    import com.opencsv.CSVReader;
    import java.io.IOException;
    import java.io.FileReader;
    
    
    ...
    
    try {
        CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            // nextLine[] is an array of values from the line
            System.out.println(nextLine[0] + nextLine[1] + "etc...");
        }
    } catch (IOException e) {
    
    }
    

    or

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    List myEntries = reader.readAll();
    

    Edit after comment

    try {
        File csvfile = new File(Environment.getExternalStorageDirectory() + "/csvfile.csv");
        CSVReader reader = new CSVReader(new FileReader(csvfile.getAbsolutePath()));
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            // nextLine[] is an array of values from the line
            System.out.println(nextLine[0] + nextLine[1] + "etc...");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
    }
    

    If you want to package the .csv file with the application and have it install on the internal storage when the app installs, create an assets folder in your project src/main folder (e.g., c:\myapp\app\src\main\assets\), and put the .csv file in there, then reference it like this in your activity:

    String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "csvfile.csv"
    File csvfile = new File(csvfileString);
    

提交回复
热议问题