简体   繁体   中英

How to use .split with new lines in a 2d array Java Android

I have a .txt file, in my assets folder which reads something like this:

I love life ;
We all dance ;
Too much pizza ;

I want to store each one of these elements into a String[] which is declared in my graphics file.

The code in my main as of right now reads

AssetManager am = getResources().getAssets();
InputStream is=null;

try {
    is = am.open("b.txt");
    InputStreamReader bFile= new InputStreamReader((is),"UTF-8");
    BufferedReader br= new BufferedReader(bFile);
    ArrayList<String> bPlaceHold= new ArrayList<String>();
    String[] bPlace2;
    String line= br.readLine();
    graphics.doing=0;                   

    while(line !=null)
    {
        bPlace2= line.split(";\n");
        bPlaceHold.add(line);
        line=br.readLine();
        graphics.doing++;           
        graphics.tester[graphics.doing]=bPlaceHold.get(graphics.doing);
    }

    br.close();
    bFile.close();

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

I've read everything I could find relating to the topic but no matter what method i try only the very first line from the file is displaying and it crashes once it trys to .get(1); Any help would be greatly appreciated I'm new to all the formalities involved in android/java programming

Your code should be like this :

graphics.tester[graphics.doing]=bPlaceHold.get(graphics.doing-1);

Reason : You are actually storing value of line at index 0 and trying to fetch the value of index one which throws you an exception. Hope this will clear your doubt.

You are adding whole string instead of splited one.

bPlaceHold.add(bPlace2[0]);

try like this instead of

bPlaceHold.add(line);

I hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM