我目前正在尝试从我创建的/main/assets 文件夹中的 list.txt 文件中获取行。
我正在尝试将此 list.txt 文件中的每一行存储到一个字符串数组,但我不确定如何在 Android Studio 中获取与 .getLine()
等效的 java?
到目前为止,这是我的代码:
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
}
如果我在这方面做错了什么,请告诉我。这是我制作的第一个 Android 应用程序之一。
编辑:
所以这就是我想要它做的:
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
我希望足够详细,感谢您的所有帮助!
最佳答案
刚刚确认使用 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);
}
这是我的文件的内容:
line 1
line 2
line 3
this is a long line
line 4
这是我的日志输出:
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
如果您提前知道文件中的行数,则可以修改 while 循环并改用 for 循环。我的文件有 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]);
}
关于java - 安卓工作室 : Storing Strings from a scanner in a String array from a file in/assets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34003962/