从文本文件中提取特定行数的最有效方法是什么?例如,如果我使用扫描仪来解析文件,我是否首先必须创建一个长度与文本文件中的总行数相匹配的数组?
如果一个文本文件有30行而我只想使用第3,第8和第12行,那么有没有办法专门读取这些行?
答案 0 :(得分:6)
这是你如何做到的:
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
int counter = 0;
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
try {
// FileReader reads text files in the default encoding.
fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 3 || counter == 8 || counter == 12)
{
// do your code
}
}
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
bufferedReader.close();
}
}
}
}
答案 1 :(得分:4)
这是你能做的。 (它只是你程序的一部分,而不是你的程序)
int counter 0 =;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
counter++;
switch(counter){
case 3:
\\ do your code for line no 3
break;
case 8:
\\ do your code for line no 8
break;
case 12:
\\ do your code for line no 12
break;
}
}
br.close();
答案 2 :(得分:3)
试试这个
try
{
String sCurrentLine;
br = new BufferedReader(new FileReader("File_Path"));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null)
{
counter++;
if (counter == 3 || counter == 8 || counter == 12)
{
System.out.println("" + br.read());
if (counter == 12)
break;
}
}
}
catch (IOException e)
{
System.out.println("Exception " + e);
}
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
答案 3 :(得分:1)
关于最后一个问题:根据此answer,Java 8允许您从文件中提取特定行。答案中提供了示例。
答案 4 :(得分:0)
在这里,您可以找到根据行号读取文件的解决方案。这个站点是最好的它包含所有编程语言中的代码。而且我已经给你了java代码。
https://www.rosettacode.org/wiki/Read_a_specific_line_from_a_file#Java