How to read a text file from “assets” directory as a string?

前端 未结 5 1504
灰色年华
灰色年华 2020-12-16 21:57

I have a file in my assets folder... how do I read it?

Now I\'m trying:

      public static String readFileAsString(String filePath)
        throws j         


        
5条回答
  •  醉酒成梦
    2020-12-16 22:30

    BufferedReader's readLine() method returns a null when the end of the file is reached, so you'll need to watch for it and avoid trying to append it to your string.

    The following code should be easy enough:

    public static String readFileAsString(String filePath) throws java.io.IOException
    {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line, results = "";
        while( ( line = reader.readLine() ) != null)
        {
            results += line;
        }
        reader.close();
        return results;
    }
    

    Simple and to-the-point.

提交回复
热议问题