替换文本文件中的列,列中包含各种空格

时间:2013-09-26 17:17:28

标签: java

我有一个包含20 000行的文本文件。作为列的数据。但列之间的空间不同,列长也不同。实施例

aaaaa ()()()()()bdo()()()()()()()()  ttttt ()() dgee ()()()()()  yyyy

bbb()()()()()()()ggg ()()()()()()()(  fff()()()(gbe()()()()()()( yHH

cc()()()()()()()()dddd()()()()()()() I ()()()()bdeg()()()()()()yyyyy

这里的空格代表括号 像那样!!!

我想用特定单词替换第N(ex:4th)列(例如:“name”)

示例输出:

aaaaa ()()()()()bdo()()()()()()()()  ttttt ()() name ()()()()()  yyyy

bbb()()()()()()()ggg ()()()()()()()(  fff()()()(name()()()()()()( yHH

cc()()()()()()()()dddd()()()()()()() I ()()()()name()()()()()()yyyyy

这里的空格代表括号 有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

public static void replaceColumn(int column, String word, File file) throws IOException {
    Scanner in = new Scanner(file);
    PrintWriter out = new PrintWriter(file);
    while (in.hasNextLine()) {
        String line = in.nextLine();
        line = line.trim();
        String columns = line.split(" ");
        columns[column] = word;
        line = arrayToString(columns, " ");
        out.println(line);
    }
    in.close();
    out.close();
}

//Helper method
private static String arrayToString(Object[] array, String separator) {
    if (array.length == 0) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    for (Object element : array) {
        sb.append(element);
        sb.append(separator);
    }
    sb.delete(sb.length - separator.length(), sb.length());
    return sb.toString();
}