0

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

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

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

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

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

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

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

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

4

4 回答 4

1

你可以尝试这样的事情:

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,则可以尝试以下操作:

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

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

replace(3, "string to replace 12345", file, strings_you_want_to_append_to_the_end); 
于 2013-08-28T03:43:21.930 回答
1

我会通过将每一行放入一个数组列表split(",")中,在数组的每一行上使用,并替换每个数组中的第 4 个索引来做到这一点。要将数组重新加入字符串,您必须编写自己的函数(Java 没有内置函数)。不过,还有另一个堆栈溢出问题可以解决这个问题。

try
    {
        Scanner scanner = new Scanner(file);

        // initialize the arraylist, which will hold the split strings
        ArrayList<String[]> data = new ArrayList<String[]>();

        while (scanner.hasNextLine())
        {
            // filling the arraylist
            String line = scanner.nextLine();
            String[] split = line.split(",");
            data.add(split);
        }
        scanner.close();

        // replacing the values
        for (String[] split : data) {
            split[3] = "new value";
        }

        // sloppily glueing everything back together
        String output = "";
        for (String[] split : data) {
            for (int i = 0; i < 5; i++) {
                if (i < 4) {output += datum + ",";}
                else {output += datum;}
            }
            output += "\n";
        }
        return output;
    }
catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }

可能真的很草率且效率低下,但这是非常合乎逻辑的。

于 2013-08-28T03:23:21.997 回答
0

您可以使用正则表达式来做到这一点:

(?<=^[^,]+,[^,]+,[^,]+,)[^,]+

例如:

private static final Pattern REGEX_PATTERN = 
        Pattern.compile("(?<=^[^,]+,[^,]+,[^,]+,)[^,]+");

public static void main(String[] args) {

    // Open input file

    // Open output file                

    // Read input line

    String inputLine = "1979,2013-08-07 19:03:35,abc,12345,310012";
    String outputLine = REGEX_PATTERN.matcher(input)
                                     .replaceFirst("YOUR_REPLACEMENT");

    // Print (only for debug)
    System.out.println(
        outputLine 
    );  // prints "1979,2013-08-07 19:03:35,abc,YOUR_REPLACEMENT,310012"

    // Write output line

    // Close both files

}
于 2013-08-28T03:43:11.960 回答
0

尝试以下

stringBuilder = new StringBuilder();
String[] resultArray = sCurrentval.split(",");

resultArray[3] = EDIT_VALVE; //your new value to replace

for (String s : resultArray)
   {
       stringBuilder.append(s);
       stringBuilder.append(",");
   }

sCurrentval = stringBuilder.append(LAST_VALUE).toString(); // add your last value
于 2013-08-28T03:57:06.023 回答