简体   繁体   中英

Android Studio: Storing Strings from a scanner in a String array from a file in /assets

I am currently trying to get the lines from a list.txt file i have in my /main/assets folder i created.

I am trying to store every line in this list.txt file to a string array but i am not sure how to get the java equivalent of .getLine() in Android Studio?

Here is my code so far:

private String[] line;
private InputStream is;
private static int NUMBER_OF_LINES = 640;
public void getLines(){
    AssetManager am = getAssets();
    try {
        is = am.open("list.txt");
    }catch(Exception e){
        Log.v("GLOBAL_VARIABLES","FILE IS NOT FOUND!");
    }
    Scanner s = new Scanner(is);
    String w[] = new String[NUMBER_OF_LINES];

    for (int i =1; i<= NUMBER_OF_LINES; i++){
        w[i] = is.toString().nextLine(); // This is what i need
    }

If i am doing anything else wrong in this please let me know. This is one of my first android app's i have made.

Edit:

So this is what i want it to do:

Read the file

Get the first line of that file

Store that line in a String array

Go to the next line

Get that line

Store that line in the String array

Rinse + repeat until the counter is up to 640

I hope that is detailed enough, Thank you for any and all help!

Just confirmed that using a LineNumberReader works.

AssetManager assets = getAssets();

try {
  InputStream in = assets.open("list.txt");
  LineNumberReader lin = new LineNumberReader(new InputStreamReader(in));
  String line;
  while((line = lin.readLine()) != null) {
    Log.i(TAG, "read a line: " + line);
  }
} catch (IOException e) {
  Log.e(TAG, "Error reading assets!", e);
}

Here is the contents of my file:

line 1
line 2
line 3
this is a long line
line 4

And here is the output from my logs:

11-30 13:10:32.730 2154-2154/mobappdev.assetstest I/AssetsTestLog: read a line: line 1
11-30 13:10:32.730 2154-2154/mobappdev.assetstest I/AssetsTestLog: read a line: line 2
11-30 13:10:32.730 2154-2154/mobappdev.assetstest I/AssetsTestLog: read a line: line 3
11-30 13:10:32.730 2154-2154/mobappdev.assetstest I/AssetsTestLog: read a line: this is a long line
11-30 13:10:32.730 2154-2154/mobappdev.assetstest I/AssetsTestLog: read a line: line 4

If you know the number of lines in your file ahead of time, you can modify the while loop and use a for loop instead. My file has 5 lines in it, so I can rewrite the above code like so:

String[] lines = new String[5];
for(int i=0; i<lines.length; i++) {
  lines[i] = lin.readLine();
  Log.i(TAG, "read line: " + lines[i]);
}

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