java for行读取文件内容_如何使用Java中的文件中的特定行号读取特定行?

如何使用Java中的文件中的特定行号读取特定行?

在Java中,是否有任何方法可以从文件中读取特定行? 例如,读取第32行或任何其他行号。

trinity asked 2019-04-18T02:23:27Z

17个解决方案

79 votes

Java 8解决方案:

对于小文件:

String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)

对于大文件:

try (Stream lines = Files.lines(Paths.get("file.txt"))) {

line32 = lines.skip(31).findFirst().get();

}

aioobe answered 2019-04-18T02:24:28Z

63 votes

除非您事先了解文件中的行,否则无法在不读取前31行的情况下直接访问第32行。

对于所有语言和所有现代文件系统都是如此。

如此有效,你只需阅读直到你找到第32行。

Joachim Sauer answered 2019-04-18T02:23:50Z

35 votes

不是我所知道的,但你可以做的是使用BufferedReader的readline()函数循环前31行无效

FileInputStream fs= new FileInputStream("someFile.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(fs));

for(int i = 0; i < 31; ++i)

br.readLine();

String lineIWant = br.readLine();

Chris Thompson answered 2019-04-18T02:24:52Z

14 votes

当然,Joachim是正确的,并且Chris的一个替代实现(对于小文件只因为它加载了整个文件)可能是使用来自Apache的commons-io(尽管可能你可能不想引入新的依赖关系) 这个,如果你发现它对其他东西也很有用,那就有意义了)。

例如:

String line32 = (String) FileUtils.readLines(file).get(31);

[http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readLines(java.io.File,)java.lang.String)

Charlie Collins answered 2019-04-18T02:25:26Z

8 votes

您可以尝试索引文件阅读器(Apache License 2.0)。 IndexedFileReader类有一个名为readLines(int from,int to)的方法,它返回一个SortedMap,其键是行号,值是读取的行。

例:

File file = new File("src/test/resources/file.txt");

reader = new IndexedFileReader(file);

lines = reader.readLines(6, 10);

assertNotNull("Null result.", lines);

assertEquals("Incorrect length.", 5, lines.size());

assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));

assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));

assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));

assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));

assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));

上面的示例按以下格式读取由50行组成的文本文件:

[1] The quick brown fox jumped over the lazy dog ODD

[2] The quick brown fox jumped over the lazy dog EVEN

免责声明:我写了这个库

jramoyo answered 2019-04-18T02:26:06Z

4 votes

虽然如在其他答案中所述,但是在不知道之前的偏移(指针)的情况下不可能到达确切的线。 所以,我通过创建一个临时索引文件来实现这一点,该文件将存储每一行的偏移值。 如果文件足够小,您可以将索引(偏移量)存储在内存中,而不需要单独的文件。

The offsets can be calculated by using the RandomAccessFile

RandomAccessFile raf = new RandomAccessFile("myFile.txt","r");

//above 'r' means open in read only mode

ArrayList arrayList = new ArrayList();

String cur_line = "";

while((cur_line=raf.readLine())!=null)

{

arrayList.add(raf.getFilePointer());

}

//Print the 32 line

//Seeks the file to the particular location from where our '32' line starts

raf.seek(raf.seek(arrayList.get(31));

System.out.println(raf.readLine());

raf.close();

另请访问java文档以获取更多信息:[https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#mode]

复杂性:这是O(n),因为它读取整个文件一次。 请注意内存要求。 如果它太大而不能在内存中,那么创建一个临时文件来存储偏移而不是ArrayList,如上所示。

注意:如果你想要在'32'行中,你只需要通过其他类'32'调用readLine()。 如果您想多次获取特定行(基于行号),则上述方法很有用。

谢谢 !

ShankarDaruga answered 2019-04-18T02:26:59Z

3 votes

不,除非以该文件格式预先确定行长度(例如,所有具有固定长度的行),否则您将必须逐行迭代以对它们进行计数。

b.roth answered 2019-04-18T02:27:24Z

3 votes

其他方式。

try (BufferedReader reader = Files.newBufferedReader(

Paths.get("file.txt"), StandardCharsets.UTF_8)) {

List line = reader.lines()

.skip(31)

.limit(1)

.collect(Collectors.toList());

line.stream().forEach(System.out::println);

}

rhel.user answered 2019-04-18T02:27:43Z

2 votes

如果你在谈论一个文本文件,那么在没有阅读它之前的所有行的情况下真的没有办法做到这一点 - 毕竟,行是由换行符的存在决定的,所以必须要读取它。

使用支持readline的流,只读取第一行X-1行并转储结果,然后处理下一行。

Uri answered 2019-04-18T02:28:15Z

2 votes

在Java 8中,

对于小文件:

String line = Files.readAllLines(Paths.get("file.txt")).get(n);

对于大文件:

String line;

try (Stream lines = Files.lines(Paths.get("file.txt"))) {

line = lines.skip(n).findFirst().get();

}

在Java 7中

String line;

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {

for (int i = 0; i < n; i++)

br.readLine();

line = br.readLine();

}

来源:从文件中读取第n行

Sid answered 2019-04-18T02:28:58Z

1 votes

这个对我有用:我结合了答案阅读一个简单的文本文件

但是我没有返回一个字符串,而是返回一个字符串的LinkedList。 然后我可以选择我想要的线。

public static LinkedList readFromAssets(Context context, String filename) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));

LinkedListlinkedList = new LinkedList<>();

// do reading, usually loop until end of file reading

StringBuilder sb = new StringBuilder();

String mLine = reader.readLine();

while (mLine != null) {

linkedList.add(mLine);

sb.append(mLine); // process line

mLine = reader.readLine();

}

reader.close();

return linkedList;

}

Tachenko answered 2019-04-18T02:29:29Z

1 votes

使用此代码:

import java.nio.file.Files;

import java.nio.file.Paths;

public class FileWork

{

public static void main(String[] args) throws IOException {

String line = Files.readAllLines(Paths.get("D:/abc.txt")).get(1);

System.out.println(line);

}

}

Usman Yaqoob answered 2019-04-18T02:29:49Z

0 votes

您可以使用LineNumberReader而不是BufferedReader。 通过api。 您可以找到setLineNumber和getLineNumber方法。

Raghavendra answered 2019-04-18T02:30:13Z

0 votes

您还可以查看BufferedReader的子类LineNumberReader。 与readline方法一起,它还具有访问行号的setter / getter方法。 在从文件读取数据时跟踪读取的行数非常有用。

Ankur Shanbhag answered 2019-04-18T02:30:38Z

0 votes

public String readLine(int line){

FileReader tempFileReader = null;

BufferedReader tempBufferedReader = null;

try { tempFileReader = new FileReader(textFile);

tempBufferedReader = new BufferedReader(tempFileReader);

} catch (Exception e) { }

String returnStr = "ERROR";

for(int i = 0; i < line - 1; i++){

try { tempBufferedReader.readLine(); } catch (Exception e) { }

}

try { returnStr = tempBufferedReader.readLine(); } catch (Exception e) { }

return returnStr;

}

Cooper Scott answered 2019-04-18T02:30:55Z

0 votes

你可以使用skip()函数从头开始跳过这些行。

public static void readFile(String filePath, long lineNum) {

List list = new ArrayList<>();

long totalLines, startLine = 0;

try (Stream lines = Files.lines(Paths.get(filePath))) {

totalLines = Files.lines(Paths.get(filePath)).count();

startLine = totalLines - lineNum;

// Stream line32 = lines.skip(((startLine)+1));

list = lines.skip(startLine).collect(Collectors.toList());

// lines.forEach(list::add);

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

list.forEach(System.out::println);

}

Neelay Solanki answered 2019-04-18T02:31:20Z

-7 votes

他们都错了,我只是在大约10秒内写下这个。有了这个,我设法在main方法中调用object.getQuestion(“linenumber”)来返回我想要的任何行。

public class Questions {

File file = new File("Question2Files/triviagame1.txt");

public Questions() {

}

public String getQuestion(int numLine) throws IOException {

BufferedReader br = new BufferedReader(new FileReader(file));

String line = "";

for(int i = 0; i < numLine; i++) {

line = br.readLine();

}

return line; }}

user3526115 answered 2019-04-18T02:31:45Z

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值