[英]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. 我目前正在尝试从我创建的/ main / assets文件夹中的list.txt文件中获取行。
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? 我正在尝试将此list.txt文件中的每一行存储到一个字符串数组,但是我不确定如何在Android Studio中获取
.getLine()
的java等效项?
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.
这是我制作的第一个Android应用程序之一。
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
将该行存储在String数组中
Go to the next line
转到下一行
Get that line
得到那条线
Store that line in the String array
将该行存储在String数组中
Rinse + repeat until the counter is up to 640
漂洗+重复直到计数器达到640
I hope that is detailed enough, Thank you for any and all help! 我希望它足够详细,谢谢您的任何帮助!
Just confirmed that using a LineNumberReader works. 只需确认使用LineNumberReader即可。
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. 如果您提前知道文件中的行数,则可以修改while循环并改用for循环。 My file has 5 lines in it, so I can rewrite the above code like so:
我的文件有5行,因此我可以这样重写上面的代码:
String[] lines = new String[5];
for(int i=0; i<lines.length; i++) {
lines[i] = lin.readLine();
Log.i(TAG, "read line: " + lines[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.