读取Java中的文本文件

读取Java中的文本文件,第1张

读取Java中的文本文件

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

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;}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5500324.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存