如何从 Android Studio 中的资产读取文本文件? [英] How to read a text file from assets in Android Studio?

查看:37
本文介绍了如何从 Android Studio 中的资产读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android Studio 的资产文件目录中可能有 wifi2.txt 文件.但是,当我尝试访问它时,我不断收到 NULLPointException.我的代码如下:(非常感谢)

I have may wifi2.txt file in my assets file directory in Android Studio. However, I keep getting a NULLPointException when I try to access it. My code is below: (Thanks so much in advance)

             //CSV FILE READING
    File file = null;



    try {



        FileInputStream is = new FileInputStream(file);

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
            String line;
            Log.e("Reader Stuff",reader.readLine());
            while ((line = reader.readLine()) != null) {
                Log.e("code",line);
                String[] RowData = line.split(",");
                LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
                if (RowData.length == 4) {
                    mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
                }

            }

        } catch (IOException ex) {
           ex.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


   //Done with CSV File Reading

推荐答案

File file = null;
try {
    FileInputStream is = new FileInputStream(file);

实际上您并没有在任何地方使用 FileInputStream.就用这段代码

Actually you are not using FileInputStream anywhere. Just use this piece of code

  try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
        String line;
        Log.e("Reader Stuff",reader.readLine());
        while ((line = reader.readLine()) != null) {
            Log.e("code",line);
            String[] RowData = line.split(",");
            LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
            if (RowData.length == 4) {
                mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            }

        }

    } catch (IOException ex) {
       ex.printStackTrace();
    } 

这篇关于如何从 Android Studio 中的资产读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆