我在使用扫描仪读取文件时遇到一些问题。
我的文件具有以下格式:
第 1 行(基本符号,例如:##%%&&)。
第 2 行(数据行数,例如:70)
第3行(一些信息)
第4-74行(任意格式的一些数据,以分号作为分隔符)
我需要实现从第四行开始的循环,并允许我填充我的 ListView。 如何解决这个问题?
这是部分代码:
Scanner read = null;
Pattern b = Pattern.compile(";|\\|\n ");
String BasicSign, NumberOfFields, barcode, name, type, amount, price;
try {
Log.d(LOG_TAG1, "--- Reading from spr: ---");
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath() + File.separator + "myFile1.spr");
read = new Scanner(textFile);
read.useDelimiter(b);
while (read.hasNext()) {
BasicSign = read.next();
NumberOfFields = read.next();
barcode = read.next();
name = read.next();
amount = read.next();
price = read.next();
tvBarcode.setText(barcode123);
tvMyName.setText(name);
tvType.setText(type);
tvPrice.setText(price);
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
最佳答案
您可以逐行处理文本文件并跳过前 3 行并从第 4 行开始。这是一个简单直接的解决方案:
BufferedReader br = new BufferedReader(textfile);
br.readLine(); // skip line
br.readLine(); // skip line
br.readLine(); // skip line
String line = br.readLine(); // start in 4th line
while (line !=null) { // end of file not reached
Scanner read = new Scanner(line);
read.useDelimiter(b);
//your while loop and processing
line = br.readLine(); // read line for next iteration
}
br.close();
关于java - 从文件中读取。安卓、Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395932/