用Java读取文本文件 [英] Read text file in Java

查看:108
本文介绍了用Java读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件。我想从一行到另一行检索内容。
例如,该文件可能是200K行。我想读第78行到第2735行的内容。由于文件可能非常大,我不想将整个内容读入内存。

解决方案

这是一个可能解决方案的开始:

  public static List< String> linesFromTo(int from,int to,String fileName)
抛出FileNotFoundException,IllegalArgumentException {
返回linesFromTo(from,to,fileName,UTF-8);
}

public static List< String> linesFromTo(int from,int to,String fileName,String charsetName)
抛出FileNotFoundException,IllegalArgumentException {
$ b $ if(from> to){
抛出new IllegalArgumentException('from '>'到');

if(from< 1 || to< 1){
throw new IllegalArgumentException('from'or'to'is negative);
}

列表< String> lines = new ArrayList< String>();
扫描仪扫描=新的扫描仪(新文件(文件名),charsetName);
int lineNumber = 0; (scan.hasNextLine()&& lineNumber< to){
lineNumber ++;


String line = scan.nextLine();
if(lineNumber< from)continue;
lines.add(line);

$ b $ if(lineNumber!= to){
throw new IllegalArgumentException(fileName +没有++行);
}

return lines;
}


I have a text file. I would like to retrieve the content from one line to another line. For example, the file may be 200K lines. I want to read the content from line 78 to line 2735. Since the file may be very large, I do not want to read the whole content into the memory.

解决方案

Here's a start of a possible solution:

public static List<String> linesFromTo(int from, int to, String fileName)
        throws FileNotFoundException, IllegalArgumentException {
    return linesFromTo(from, to, fileName, "UTF-8");
}

public static List<String> linesFromTo(int from, int to, String fileName, String charsetName)
        throws FileNotFoundException, IllegalArgumentException {

    if(from > to) {
        throw new IllegalArgumentException("'from' > 'to'");
    }
    if(from < 1 || to < 1) {
        throw new IllegalArgumentException("'from' or 'to' is negative");
    }

    List<String> lines = new ArrayList<String>();
    Scanner scan = new Scanner(new File(fileName), charsetName);
    int lineNumber = 0;

    while(scan.hasNextLine() && lineNumber < to) {
        lineNumber++;
        String line = scan.nextLine();
        if(lineNumber < from) continue;
        lines.add(line);
    }

    if(lineNumber != to) {
        throw new IllegalArgumentException(fileName+" does not have "+to+" lines");
    }

    return lines;
}

这篇关于用Java读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆