简体   繁体   English

CSV:搜索String并替换为另一个字符串

[英]Csv: search for String and replace with another string

I have a .csv file that contains: 我有一个.csv文件,其中包含:

 scenario, custom,    master_data
 1,        ${CUSTOM},  A_1

I have a string: 我有一个字符串:

 a, b, c

and I want to replace 'custom' with 'a, b, c'. 我想将“ custom”替换为“ a,b,c”。 How can I do that and save to the existing .csv file? 我该怎么做并保存到现有的.csv文件?

Probably the easiest way is to read in one file and output to another file as you go, modifying it on a per-line basis 可能最简单的方法是随手读取一个文件并输出到另一个文件,然后逐行对其进行修改

You could try something with tokenizers, this may not be completely correct for your output/input, but you can adapt it to your CSV file formatting 您可以尝试使用分词器,这对于您的输出/输入而言可能并不完全正确,但是您可以将其调整为CSV文件格式

BufferedReader reader = new BufferedReader(new FileReader("input.csv"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.csv"));
String custom = "custom";
String replace = "a, b, c";

for(String line = reader.readLine(); line != null; line = reader.readLine())
{
    String output = "";
    StringTokenizer tokenizer = new StringTokenizer(line, ",");
    for(String token = tokenizer.nextToken(); tokenizer.hasMoreTokens(); token = tokenizer.nextToken())
        if(token.equals(custom)
            output = "," + replace;
        else
            output = "," + token;
}
readInventory.close();

If this is for a one off thing, it also has the benefit of not having to research regular expressions (which are quite powerful and useful, good to know, but maybe for a later date?) 如果这是一次性的事情,那么它还具有不必研究正则表达式的好处(正则表达式非常强大和有用,很容易理解,但也许以后再使用?)

Have a look at Can you recommend a Java library for reading (and possibly writing) CSV files? 看看您能推荐一个Java库来读取(并可能编写)CSV文件吗?

And once the values have been read, search for strings / value that start with ${ and end with } . 读取值之后,搜索以${开头并以}结尾的字符串/值。 Use Java Regular Expressions like \\$\\{(\\w)\\} . 使用\\$\\{(\\w)\\}类的Java正则表达式 Then use some map for looking up the found key, and the related value. 然后使用一些映射表查找找到的密钥以及相关的值。 Java Properties would be a good candidate. Java 属性将是一个不错的选择。

Then write a new csv file. 然后编写一个新的csv文件。

Since your replacement string is quite unique you can do it quickly without complicated parsing by just reading your file into a buffer, and then converting that buffer into a string. 由于替换字符串非常独特,因此只需将文件读入缓冲区,然后将该缓冲区转换为字符串,即可快速进行操作而无需进行复杂的解析。 Replace all occurrences of the text you wish to replace with your target text. 将所有希望替换的文本替换为目标文本。 Then convert the string to a buffer and write that back to the file... 然后将字符串转换为缓冲区并将其写回到文件中。

Pattern.quote is required because your string is a regular expression. 因为您的字符串是一个正则表达式,所以需要使用Pattern.quote。 If you don't quote it you may run into unexpected results. 如果不引用它,可能会遇到意想不到的结果。

Also it's generally not smart to overwrite your source file. 同样,覆盖源文件通常也不明智。 Best is to create a new file then delete the old and rename the new to the old. 最好是先创建一个新文件,然后删除旧文件,然后将新文件重命名为旧文件。 Any error halfway will then not delete all your data. 中途出现任何错误都不会删除您的所有数据。

final Path yourPath = Paths.get("Your path");
byte[] buff = Files.readAllBytes(yourPath);
String s = new String(buff, Charset.defaultCharset());
s = s.replaceAll(Pattern.quote("${CUSTOM}"), "a, b, c");
Files.write(yourPath, s.getBytes());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM