read file from assets

前端 未结 18 2266
终归单人心
终归单人心 2020-11-21 22:47
public class Utils {
    public static List getMessages() {
        //File file = new File(\"file:///android_asset/helloworld.txt\");
        AssetMan         


        
18条回答
  •  后悔当初
    2020-11-21 23:47

    Better late than never.

    I had difficulties reading files line by line in some circumstances. The method below is the best I found, so far, and I recommend it.

    Usage: String yourData = LoadData("YourDataFile.txt");

    Where YourDataFile.txt is assumed to reside in assets/

     public String LoadData(String inFile) {
            String tContents = "";
    
        try {
            InputStream stream = getAssets().open(inFile);
    
            int size = stream.available();
            byte[] buffer = new byte[size];
            stream.read(buffer);
            stream.close();
            tContents = new String(buffer);
        } catch (IOException e) {
            // Handle exceptions here
        }
    
        return tContents;
    
     }
    

提交回复
热议问题