从 android 中的 .txt 文件读取特定行
Reading specific line fromt .txt file in android
我得到了文件,它的大小和行数可能会有所不同。我唯一知道的是它由相同的模块组成,比方说,7 行。所以这意味着 .txt 可以是 7、14、21、70、77 等行。我只需要获取每个模块的 header - 第 0、7 行等等。
我已经为这份工作编写了这段代码:
textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );
List<String> headers = new ArrayList<>();
if (textFile.exists()) {
try {
FileInputStream fs= new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
int lines = 0;
int headLine = 0;
while (reader.readLine() != null) { lines++;}
Log.i("Debug", Integer.toString(lines));
while(headLine < lines){
for (int i = 0; i < dateLine - 1; i++)
{
reader.readLine();
Log.i("Debug", reader.readLine());
}
headers.add(reader.readLine());
headLine += 7;
}
Log.i("Debug", headers.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
问题是它总是 returns [null]。我不知道哪里出了问题,因为我参考了overflow的类似问题。
ArrayList<String> headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
// process the line.
if(lineCount % 7 == 0) {
heaaderLines.add(line);
}
lineCount ++;
}
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
br.close();
}
我得到了文件,它的大小和行数可能会有所不同。我唯一知道的是它由相同的模块组成,比方说,7 行。所以这意味着 .txt 可以是 7、14、21、70、77 等行。我只需要获取每个模块的 header - 第 0、7 行等等。
我已经为这份工作编写了这段代码:
textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );
List<String> headers = new ArrayList<>();
if (textFile.exists()) {
try {
FileInputStream fs= new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
int lines = 0;
int headLine = 0;
while (reader.readLine() != null) { lines++;}
Log.i("Debug", Integer.toString(lines));
while(headLine < lines){
for (int i = 0; i < dateLine - 1; i++)
{
reader.readLine();
Log.i("Debug", reader.readLine());
}
headers.add(reader.readLine());
headLine += 7;
}
Log.i("Debug", headers.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
问题是它总是 returns [null]。我不知道哪里出了问题,因为我参考了overflow的类似问题。
ArrayList<String> headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
// process the line.
if(lineCount % 7 == 0) {
heaaderLines.add(line);
}
lineCount ++;
}
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
br.close();
}