Java的:读取文本文件到一个数组 [英] Java: Read a text file into an array

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

问题描述

我有两列像这样由一个txt文件:

_名1选项1
名称2 _ OPT2
NAME3 _ OPT3

在每一行有一个名称,一个标签分隔符,一_然后另一个名字;真的有许多行(约15万),我甚至不知道哪一个是使用,我想一个二维数组最好的构造函数,但它可能是还别的东西,如果它是一个更好的选择。对我来说,我可以接触到的元素像这样一个[X] [Y]是很重要的。
我这样做,但我只知道如何计算的行数或如何将每个线阵列的不同位置。
这里的code:

  INT countLine = 0;
    读者的BufferedReader =新的BufferedReader(新的FileReader(文件名));
    而(真){
        串行= reader.readLine();
        如果(行== NULL){
            reader.close();
            打破;
        }其他{
            countLine ++;
        }
    }


解决方案

既然你不知道提前行数,我会使用的ArrayList 代替的阵列。线成字符串值的拆分可以很容易地用常规的前pression完成。

模式模式= Pattern.compile((*)\\ T_ \\ T(*)。);
清单<的String []>名单=新的ArrayList<>();
INT countLine = 0;读者的BufferedReader =新的BufferedReader(新的FileReader(文件名));
而(真){
    串行= reader.readLine();
    如果(行== NULL){
        reader.close();
        打破;
    }其他{
        匹配器匹配= pattern.matcher(线);
        如果(matcher.matches()){
            list.add(新的String [] {m​​atcher.group(1),matcher.group(2)});
        }
        countLine ++;
    }

I've a txt file composed by two columns like this:

Name1     _     Opt1
Name2     _     Opt2
Name3     _     Opt3

In each row there's a name, a tab delimiter, a _ and then another name; there are really many rows (about 150000) and i'm not even sure which one is the best constructor to use, i'm thinking about a two dimensional array but it could be also something else if it's a better choice. For me it's important that i can access to the elements with something like this a[x][y]. I've done this but i just know how to count the number of the lines or how to put each lines in a different position of an array. Here's the code:

int countLine = 0;
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            reader.close();
            break;
        } else {
            countLine++;
        }
    }

解决方案

Since you don't know the number of lines ahead of time, I would use an ArrayList instead of an array. The splitting of lines into String values can easily be done with a regular expression.

Pattern pattern = Pattern.compile("(.*)\t_\t(.*)");
List<String[]> list = new ArrayList<>();
int countLine = 0;

BufferedReader reader = new BufferedReader(new FileReader(filename));
while (true) {
    String line = reader.readLine();
    if (line == null) {
        reader.close();
        break;
    } else {
        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            list.add(new String[] { matcher.group(1), matcher.group(2) });
        }
        countLine++;
    }

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

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