从.txt文件JAVA中读取特定数据

时间:2015-09-13 18:54:56

标签: java file

我有问题。我正在尝试读取一个大的.txt文件,但我不需要内部的每一段数据。

我的.txt文件看起来像这样:

  

8000000 abcdefg hijklmn单词字母

我只需要,比方说,数字和前两个文本位置:“abcdefg”和“hijklmn”,然后将其写入另一个文件。我不知道如何只读取和写入我需要的数据。

到目前为止,这是我的代码:

    BufferedReader br = new BufferedReader(new FileReader("position2.txt"));
    BufferedWriter bw = new BufferedWriter(new FileWriter("position.txt"));
    String line;

    while ((line = br.readLine())!= null){
        if(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")){
            continue;
        }else{
            //bw.write(line + "\n");
            String[] data = line.split(" ");
            bw.write(data[0] + " " + data[1] + " " + data[2] + "\n");
        }

    }

    br.close();
    bw.close();

}
你能给我一些消化吗? 提前致谢

更新: 我的.txt文件有点奇怪。当它们之间只有一个单独的“”时,使用上面的代码很有效。我的文件可以有一个\ t或更多的空格,或者一个\ t和单词之间的空格。我现在可以继续吗?

3 个答案:

答案 0 :(得分:2)

根据数据的复杂程度,您有几个选择。

如果这些行是如图所示的简单空格分隔值,最简单的方法是拆分文本,并将要保留的值写入新文件:

try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] values = line.split(" ");
        if (values.length >= 3)
            bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
    }
}

如果值可能更复杂,则可以使用正则表达式:

Pattern p = Pattern.compile("^(\\d+ \\w+ \\w+)");
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        Matcher m = p.matcher(line);
        if (m.find())
            bw.write(m.group(1) + '\n');
    }
}

这可确保第一个值仅为数字,第二个和第三个值仅为字符(a-z A-Z _ 0-9)。

答案 1 :(得分:0)

else {
     String[] res = line.split(" ");
     bw.write(res[0] + " " + res[1] + " " + res[2] + "\n"); // the first three words...
}

答案 2 :(得分:0)

如果你的文件真的很大(超过50-100 MB,可能是GB),你确定第一个单词是一个数字,之后你需要两个单词,我建议你读一行并迭代该字符串。当你找到第三个空间时停止。

String str = readLine();
int num_spaces = 0, cnt = 0;
String arr[] = new String[3];
while(num_spaces < 3){
    if(str.charAt(cnt) == ' '){
        num_space++;
    }
    else{
        arr[num_space] += str.charAt(cnt);
    }
}

如果您的数据仅为MB,或者内部有很多数字,则无需担心按字符串迭代char。只提到read line by line and split lines then check the words

相关问题