1

I have a .csv file that contains:

 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'. How can I do that and save to the existing .csv file?

user1607549
  • 1,499
  • 3
  • 13
  • 17
  • In general, you don't save to the existing `.csv` file - you save to a temporary file, and then replace the old file with it. – RealSkeptic Oct 26 '15 at 20:16

3 Answers3

0

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

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?)

phflack
  • 2,729
  • 1
  • 9
  • 21
0

Have a look at Can you recommend a Java library for reading (and possibly writing) CSV files?

And once the values have been read, search for strings / value that start with ${ and end with }. Use Java Regular Expressions like \$\{(\w)\}. Then use some map for looking up the found key, and the related value. Java Properties would be a good candidate.

Then write a new csv file.

Community
  • 1
  • 1
Verhagen
  • 3,885
  • 26
  • 36
0

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. 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());
willow512
  • 122
  • 1
  • 7