如何从 Android Studio 中的资源中读取文本文件?

gar*_*wer 3 android nullpointerexception android-assets android-studio

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

             //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
Run Code Online (Sandbox Code Playgroud)

小智 6

在 Kotlin 中,我们可以实现这一点:-

val string = requireContext().assets.open("wifi2.txt").bufferedReader().use {
                it.readText()
            }
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 5

File file = null;
try {
    FileInputStream is = new FileInputStream(file);
Run Code Online (Sandbox Code Playgroud)

实际上你没有在任何地方使用 FileInputStream 。只需使用这段代码

  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();
    } 
Run Code Online (Sandbox Code Playgroud)