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

前端 未结 5 1497
灰色年华
灰色年华 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:34

    I wrote a function that does the same thing as yours. I wrote it a while back but I believe it still works correctly.

    public static final String grabAsSingleString(File fileToUse) 
                throws FileNotFoundException {
    
            BufferedReader theReader = null;
            String returnString = null;
    
            try {
                theReader = new BufferedReader(new FileReader(fileToUse));
                char[] charArray = null;
    
                if(fileToUse.length() > Integer.MAX_VALUE) {
                    // TODO implement handling of large files.
                    System.out.println("The file is larger than int max = " +
                            Integer.MAX_VALUE);
                } else {
                    charArray = new char[(int)fileToUse.length()];
    
                    // Read the information into the buffer.
                    theReader.read(charArray, 0, (int)fileToUse.length());
                    returnString = new String(charArray);
    
                }
            } catch (FileNotFoundException ex) {
                throw ex;
            } catch(IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    theReader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
    
            return returnString;
        }
    

    Now you can use this function if you wish, but when you're passing in the file either through a file object or a string, make sure you either give the full path of the file such as "C:\Program Files\test.dat" OR you pass in the relative link from your working directory. Your working directory is commonly the directory you launch the application from (unless you change it). So if the file was in a folder called data, you would pass in "./data/test.dat"

    Yes, I know this is working with android so the Windows URI isn't applicable, but you should get my point.

提交回复
热议问题