在Android应用中读取CSV文件

27

我正在开发一个概念验证应用程序,以便我可以在正在制作的更大型的应用程序中实现该功能。我对Java和Android Dev有点陌生,但希望这不会是一个太简单或太复杂的问题。

基本上,我正在尝试从CSV文件中读取字符串列表,并使其可用于在应用程序的主活动中显示列表。

我正在使用外部类来读取CSV。以下是类代码:

CSVFile.java

package com.yourtechwhiz.listdisplay;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CSVFile {
    InputStream inputStream;

    public CSVFile(InputStream inputStream){
        this.inputStream = inputStream;
    }

    public List read(){
        List resultList = new ArrayList();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            String csvLine;
            while ((csvLine = reader.readLine()) != null) {
                String[] row = csvLine.split(",");
                resultList.add(row);
                Log.d("VariableTag", row[0].toString());
            }
        }
        catch (IOException ex) {
            throw new RuntimeException("Error in reading CSV file: "+ex);
        }
        finally {
            try {
                inputStream.close();
            }
            catch (IOException e) {
                throw new RuntimeException("Error while closing input stream: "+e);
            }
        }
        return resultList;
    }
}

这是我的主要活动代码:

MainActivity.java

package com.yourtechwhiz.listdisplay;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // Array of strings that's used to display on screen
    String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
            "WebOS","Ubuntu","Windows7","Max OS X"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prepArray();

        //Display List on Activity
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.activity_listview, mobileArray);
        ListView listView = (ListView) findViewById(R.id.mobile_list);
        listView.setAdapter(adapter);

    }

    //Get list of strings from CSV ready to use
    private void prepArray() {

        InputStream inputStream = getResources().openRawResource(R.raw.strings);
        CSVFile csvFile = new CSVFile(inputStream);
        List myList = csvFile.read();

        //This is where it has an error
        //Set first array in myList to this new array myArray
        String[] myArray = myList.get(0);

    }

}

我实际上还没有到设置mobileArray数组的要点。现在我只是尝试从List对象myList中“提取”信息...

有人能解释一下这是如何完成的吗?也许我没有完全理解List类型。似乎当CSVFile读取方法返回resultList时,它返回一个由String数组对象组成的List对象。但我无法让它像那样工作。

任何帮助都将不胜感激!

最终编辑(可工作代码)

private void prepArray() {

        try{
            CSVReader reader = new CSVReader(new InputStreamReader(getResources().openRawResource(R.raw.strings)));//Specify asset file name
            String [] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                System.out.println(nextLine[0] + nextLine[1] + "etc...");
                Log.d("VariableTag", nextLine[0]);
            }
        }catch(Exception e){
            e.printStackTrace();
            Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
        }

    }

编辑

现在我的prepArray函数看起来像这样:

    private void prepArray() {

        try{
            String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "strings.csv"
            File csvfile = new File(csvfileString);
            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(FileNotFoundException e){
            e.printStackTrace();
            Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
        }

    }

仍然会产生FileNotFoundException。

编辑2/3

这是在实际手机上运行应用程序时生成的日志,其中strings.csv位于strings子文件夹中(src\main\assets\strings\strings.csv),并且代码已按照您要求进行更改:

03/27 17:44:01: Launching app
        $ adb push C:\Users\Roy\AndroidStudioProjects\ListDisplay\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.yourtechwhiz.listdisplay
        $ adb shell pm install -r "/data/local/tmp/com.yourtechwhiz.listdisplay"
        pkg: /data/local/tmp/com.yourtechwhiz.listdisplay
        Success


        $ adb shell am start -n "com.yourtechwhiz.listdisplay/com.yourtechwhiz.listdisplay.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
        Connecting to com.yourtechwhiz.listdisplay
        D/HyLog: I : /data/font/config/sfconfig.dat, No such file or directory (2)
        D/HyLog: I : /data/font/config/dfactpre.dat, No such file or directory (2)
        D/HyLog: I : /data/font/config/sfconfig.dat, No such file or directory (2)
        W/ActivityThread: Application com.yourtechwhiz.listdisplay is waiting for the debugger on port 8100...
        I/System.out: Sending WAIT chunk
        I/dalvikvm: Debugger is active
        I/System.out: Debugger has connected
        I/System.out: waiting for debugger to settle...
        Connected to the target VM, address: 'localhost:8609', transport: 'socket'
        I/System.out: waiting for debugger to settle...
        I/System.out: waiting for debugger to settle...
        I/System.out: waiting for debugger to settle...
        I/System.out: waiting for debugger to settle...
        I/System.out: waiting for debugger to settle...
        I/System.out: waiting for debugger to settle...
        I/System.out: waiting for debugger to settle...
        I/System.out: debugger has settled (1498)
        I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
        W/dalvikvm: VFY: unable to resolve interface method 16152: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
        D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
        W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
        I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
        W/dalvikvm: VFY: unable to resolve interface method 16154: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
        D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
        I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
        W/dalvikvm: VFY: unable to resolve interface method 16158: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
        D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
        I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
        W/dalvikvm: VFY: unable to resolve virtual method 455: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
        D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
        I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
        W/dalvikvm: VFY: unable to resolve virtual method 477: Landroid/content/res/TypedArray;.getType (I)I
        D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
        I/dalvikvm: Could not find method android.widget.FrameLayout.startActionModeForChild, referenced from method android.support.v7.widget.ActionBarContainer.startActionModeForChild
        W/dalvikvm: VFY: unable to resolve virtual method 16589: Landroid/widget/FrameLayout;.startActionModeForChild (Landroid/view/View;Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
        D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
        I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v7.content.res.AppCompatResources.getColorStateList
        W/dalvikvm: VFY: unable to resolve virtual method 269: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
        D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
        I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
        W/dalvikvm: VFY: unable to resolve virtual method 418: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
        D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
        I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
        W/dalvikvm: VFY: unable to resolve virtual method 420: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
        D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
        E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
        W/dalvikvm: VFY: unable to resolve instanceof 140 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
        D/dalvikvm: VFY: replacing opcode 0x20 at 0x000c
        W/System.err: java.io.FileNotFoundException: /csvfile.getAbsolutePath(): open failed: ENOENT (No such file or directory)
        W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:462)
        W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:78)
        W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:105)
        W/System.err:     at java.io.FileReader.<init>(FileReader.java:66)
        W/System.err:     at com.yourtechwhiz.listdisplay.MainActivity.prepArray(MainActivity.java:43)
        W/System.err:     at com.yourtechwhiz.listdisplay.MainActivity.onCreate(MainActivity.java:26)
        W/System.err:     at android.app.Activity.performCreate(Activity.java:5287)
        W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2145)
        W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2231)
        W/System.err:     at android.app.ActivityThread.access$700(ActivityThread.java:139)
        W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1401)
        W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
        W/System.err:     at android.os.Looper.loop(Looper.java:137)
        W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5082)
        W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
        W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
        W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
        W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:598)
        W/System.err:     at dalvik.system.NativeStart.main(Native Method)
        W/System.err: Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
        W/System.err:     at libcore.io.Posix.open(Native Method)
        W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
        W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:446)
        W/System.err:   ... 19 more
        I/Adreno-EGL: <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build:  ()
        OpenGL ES Shader Compiler Version: E031.24.00.01
        Build Date: 12/27/13 Fri
        Local Branch: qualcomm_only
        Remote Branch:
        Local Patches:
        Reconstruct Branch:
        D/OpenGLRenderer: Enabling debug mode 0
        D/OpenGLRenderer: GL error from OpenGLRenderer: 0x502
        E/OpenGLRenderer:   GL_INVALID_OPERATION

注意:csvLine.split(",")对于列内的逗号无法正确工作。 - OneCricketeer
7个回答

48

试试OpenCSV - 它会让你的生活更轻松。

首先,按照以下方式将此包添加到您的gradle依赖项中。


(Try OpenCSV - it will make your life easier. First, add this package to your gradle dependencies as follows.)
implementation 'com.opencsv:opencsv:4.6'

然后你可以选择执行

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) {

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

评论后编辑

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

如果您想将.csv文件与应用程序一起打包,并且在应用程序安装时将其安装在内部存储中,请在项目的src/main文件夹(例如c:\myapp\app\src\main\assets\)中创建一个assets文件夹,并将.csv文件放在其中,然后在您的活动中像这样引用它:

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

在实际设备上运行它,或尝试将CSV文件放入子目录中,例如c:\ myproject \ app \ src \ main \ assets \ strings \ strings.csv,并将“String csvfileString”更改为“String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar +“strings”+ File.separatorChar +“strings.csv””。 - buradd
好的!我很高兴地报告问题已经解决了。经过一些研究和重新思考,我发现之前我是通过使用getResource.getRawResource来访问我的strings.csv文件的原始资源文件夹。我已经在上面的prepArray方法中发布了最终编辑。感谢您的帮助! - TheBlindDeveloper
2
@buradd 有些问题出现了。我收到了这个错误:在查找catch块时未解决异常类:java.beans.IntrospectionException;;;;由于:java.lang.NoClassDefFoundError:无法解析:Ljava/beans/Introspector; - Dr.jacky
1
看起来像是android没有包含java.beans.Introspector,而这对于一些OpenCSV类是必要的。具体可以参考stackoverflow的这个链接 - DasMoeh
那给了我一个错误... 造成原因是:java.io.FileNotFoundException: /data/user/0/com.exa.myapp/csvfile.csv: 打开失败:ENOENT(没有这样的文件或目录) - Liker777
显示剩余7条评论

10
以下代码片段从“raw”资源文件夹中读取CSV文件(在编译时将打包进您的“.apk”文件中)。
Android默认不会创建“raw”文件夹。请在您的项目下“res/raw”目录下创建一个“raw”文件夹,并将CSV文件复制到其中。文件名应该为小写,并在需要时将其转换为文本格式。我的CSV文件名为“welldata.csv”。
在这个片段中,“WellData”是模型类(带有构造函数、getter和setter),而“wellDataList”是用于存储数据的ArrayList。
private void readData() {
    InputStream is = getResources().openRawResource(R.raw.welldata);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is, Charset.forName("UTF-8")));
    String line = "";

    try {
        while ((line = reader.readLine()) != null) {
           // Split the line into different tokens (using the comma as a separator).
            String[] tokens = line.split(",");

            // Read the data and store it in the WellData POJO.
            WellData wellData = new WellData();
            wellData.setOwner(tokens[0]);
            wellData.setApi(tokens[1]);
            wellData.setLongitude(tokens[2]);
            wellData.setLatitude(tokens[3]);
            wellData.setProperty(tokens[4]);
            wellData.setWellName(tokens[5]);
            wellDataList.add(wellData);

            Log.d("MainActivity" ,"Just Created " + wellData);
        }
    } catch (IOException e1) {
        Log.e("MainActivity", "Error" + line, e1);
        e1.printStackTrace();
    }
}

8

以下是 Kotlin 中适用的代码示例。你需要将 myfile.csv 文件放置在 res/raw 文件夹中,如果该文件夹不存在则需要手动创建。

val inputStream: InputStream = resources.openRawResource(R.raw.myfile)
val reader = BufferedReader(InputStreamReader(inputStream, Charset.forName("UTF-8")))
reader.readLines().forEach {

    //get a string array of all items in this line
    val items = it.split(",")

    //do what you want with each item
}

编辑:如果您的任何项目包含“,”,则此方法不适用。


我尝试运行它,但出现了错误...未解决的引用:myfile。建议创建myfile.xml... - Liker777
刚刚解决了我之前的评论:我把文件命名为"import.csv",而"import"是Java的关键字-这导致了一个错误。 - Liker777
我认为这种行不会起作用:col 1,“col,2”,“col”“3”,“col(换行)4” - fikr4n

2

新手使用Android Studio。我一直在研究如何读取CSV文件,这是最适合我需求的方法。(s0、s1等字符串在我的程序开头被定义)。

    File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File fileToGet = new File(fileDirectory,"aFileName.csv");
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileToGet));
            String line;
            while ((line = br.readLine()) !=null) {
                String[] tokens = line.split(",");
                s0=tokens[0].toString(); s1=tokens[1].toString(); s2=tokens[2].toString();
                s3=tokens[3].toString(); s4=tokens[4].toString(); s5=tokens[5].toString();
                                                  }
            }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

这个解决方案有点幼稚 - 它不能处理包含逗号值的列。"第一列","带有逗号的列"是一个包含2列的有效CSV行。 - Shadow
你节省了我的时间。谢谢。 - Show Young Soyinka

0

这里有一个简单的方法,对我很有效。

MainActivity.java

// Do not forget to call readWeatherData() in onCreate or wherever you need to :)

// Defining ordered collection as WeatherSample class
private List<WeatherSample> weatherSamples = new ArrayList<>();

private void readWeatherData() {
    // Read the raw csv file
    InputStream is = getResources().openRawResource(R.raw.data);

    // Reads text from character-input stream, buffering characters for efficient reading
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is, Charset.forName("UTF-8"))
    );

    // Initialization
    String line = "";

    // Initialization
    try {
        // Step over headers
        reader.readLine();

        // If buffer is not empty
        while ((line = reader.readLine()) != null) {
            Log.d("MyActivity","Line: " + line);
            // use comma as separator columns of CSV
            String[] tokens = line.split(",");
            // Read the data
            WeatherSample sample = new WeatherSample();

            // Setters
            sample.setMonth(tokens[0]);
            sample.setRainfall(Double.parseDouble(tokens[1]));
            sample.setSumHours(Integer.parseInt(tokens[2]));

            // Adding object to a class
            weatherSamples.add(sample);

            // Log the object
            Log.d("My Activity", "Just created: " + sample);
        }

    } catch (IOException e) {
        // Logs error with priority level
        Log.wtf("MyActivity", "Error reading data file on line" + line, e);

        // Prints throwable details
        e.printStackTrace();
    }
}

WeatherSample.java

public class WeatherSample {
private String month;
private double rainfall;
private int sumHours;

public String getMonth() {
    return month;
}

public void setMonth(String month) {
    this.month = month;
}

public double getRainfall() {
    return rainfall;
}

public void setRainfall(double rainfall) {
    this.rainfall = rainfall;
}

public int getSumHours() {
    return sumHours;
}

public void setSumHours(int sumHours) {
    this.sumHours = sumHours;
}

@Override
public String toString() {
    return "WeatherSample{" +
            "month='" + month + '\'' +
            ", rainfall=" + rainfall +
            ", sumHours=" + sumHours +
            '}';
}

}

关于您的源CSV文件,首先创建目录:
app -> res(右键单击) -> 新建 -> Android资源目录 -> 资源类型(原始) -> 确定

然后将您的.csv文件复制并粘贴到新出现的目录中:
原始(右键单击) -> 在资源管理器中显示

这是我用于该项目的源文件:
data.csv

如果您仍然遇到一些错误,这里有一个链接到完整项目的链接:
源代码

希望能对您有所帮助,祝您玩得愉快 :)


欢迎来到Stack Overflow!虽然链接是分享知识的好方法,但如果它们在未来失效,它们实际上无法回答问题。在您的答案中添加回答问题的链接的基本内容。如果内容过于复杂或太大无法适应此处,请描述建议解决方案的一般思路。记得始终保留原始解决方案网站的链接参考。详情请参阅: 如何撰写优秀答案? - sɐunıɔןɐqɐp

0
在最新的Android 11版本中,你需要做类似于这样的事情:
val reader = CSVReader(
            getApplication<Application>().applicationContext.assets.open("file-name.csv")
                .reader()
        )
        val myEntries: List<Array<String>> = reader.readAll()

build.gradle(应用级别)中:
dependencies {
    ...

    // CSV reader
    implementation 'com.opencsv:opencsv:4.6'
}

AndroidManifest.xml 文件中:
    <application
        android:requestLegacyExternalStorage="true"
        ...

0

在文件夹res/raw中有一个名为filename.csv的文件:

   private void gettingItemsFromCSV() {

    BufferedInputStream bufferedInputStream = new BufferedInputStream(getResources().openRawResource(R.raw.filename));
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(bufferedInputStream));

    try {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            Log.i("Test123", line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接