Java逐行读取文件并替换第n列 [英] Java read file line by line and replace nth column

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

问题描述

说以下是我的文件内容(数百个相同的模式行)

Say the following is my file content (hundreds of same pattern lines)

    1979,2013-08-07 19:03:35,abc,12345,310012
    1980,2013-08-07 19:05:03,fds,12345,310160
.
.

我想读取文件并逐行扫描文件,并将该行的第4列(在所有行上重复的12345)替换为另一个值,并在每行的末尾添加一个新值.

I want to read the file and scan the file line by line and replace the 4th column of the line (12345 which repeats on all the lines) to another value as well as adding a new value at the end of each line.

最后,我需要使用更新后的值重新生成文件作为输出.

Finally I need to regenerate the file with the updated values as an output.

这是我到目前为止所做的:

here is what I do so far:

URL path = ClassLoader.getSystemResource("test.txt");

        File file = new File(path.toURI());

        try
        {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine())
            {
                String line = scanner.nextLine();

                // Here I need to do the replacement codes
            }
            scanner.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

将每一行拆分为一个数组并执行类似的处理是个好主意吗?还是有更好的解决方案?

Is it a good idea to split each line to an array and do the processes like that or is there any better solution for this?

我也不确定如何使用编辑后的内容创建输出.任何帮助将不胜感激.

I am also not sure how to create an output with the edited content. Any help would be appreciated.

推荐答案

您可以尝试以下方法:

public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
    assert column >= 0 : "column < 0";
    final List<String> lines = new LinkedList<String>();
    final Scanner reader = new Scanner(file, "UTF-8");
    while(reader.hasNextLine()){
        final String line = reader.nextLine().trim();
        if(line.isEmpty())
            continue;
        final String[] tokens = line.split(",");
        assert column < tokens.length-1 : "column > tokens.length-1";
        tokens[column] = replacement;
        final StringBuilder builder = new StringBuilder();
        for(final String token : tokens)
            builder.append(token + ",");
        for(final String append : appends)
            builder.append(append + ",");
        builder.deleteCharAt(builder.length()-1);
        lines.add(builder.toString());
    }
    reader.close();
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
    for(final String line : lines){
        writer.write(line);
        writer.newLine();
    }
    writer.flush();
    writer.close();
}

或者,如果您使用的是Java 8,则可以尝试执行以下操作:

Or if you are using Java 8, you could try something like this:

public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
    assert column >= 0 : "column < 0";
    final List<String> lines = new LinkedList<>();
    final Scanner reader = new Scanner(file, "UTF-8");
    while(reader.hasNextLine()){
        final String line = reader.nextLine().trim();
        if(line.isEmpty())
            continue;
        final String[] tokens = line.split(",");
        assert column < tokens.length-1 : "column > tokens.length-1";
        tokens[column] = replacement;
        final List<String> temp = new LinkedList<>();
        temp.addAll(Arrays.asList(tokens));
        temp.addAll(Arrays.asList(appends));
        lines.add(temp.stream().collect(Collectors.joining(",")));
    }
    reader.close();
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
    lines.forEach(
            l -> {
                try{
                    writer.write(l);
                    writer.newLine();
                }catch(IOException ex){
                    ex.printStackTrace();
                }
            }
    );
    writer.flush();
    writer.close();
}

要调用此方法,您可以执行以下操作:

To call this method, you could do something like this:

replace(3, "string to replace 12345", file, strings_you_want_to_append_to_the_end); 

这篇关于Java逐行读取文件并替换第n列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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