[JAVA] String replacement

Replace date strings in Java.

Java



package example;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class ReplaceTestDate {

    public static void main(String[] args) {

        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;

        String todayMinus1 = localDate.minusDays(1).format(formatter);
        String today = localDate.format(formatter);
        String todayPlus1 = localDate.plusDays(1).format(formatter);
        String todayPlus2 = localDate.plusDays(2).format(formatter);

        String[] lines = {
                "\"1\", \"2\", \"a\", \"b\", \"Ah\", \"$_TODAY_MINUS_1_$\"",
                "\"1\", \"2\", \"a\", \"b\", \"$_TODAY_$\", \"Ah\"",
                "\"1\", \"2\", \"a\", \"$_TODAY_PLUS_1_$\", \"b\", \"Ah\"",
                "\"1\", \"2\", \"$_TODAY_PLUS_2_$\", \"a\", \"b\", \"Ah\"",
        };

        Path csvFile = Paths.get("CSV/ReplaceTestDate.csv");
        Path backupFile = Paths.get("CSV/ReplaceTestDate_orig.csv");
        StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;

        try (FileOutputStream fos = new FileOutputStream(csvFile.toString(), true);
                OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw)) {

            Files.copy(csvFile, backupFile, copyOption);

            for (String line : lines) {
                String replacedLine = line
                        .replace("$_TODAY_MINUS_1_$", todayMinus1)
                        .replace("$_TODAY_$", today)
                        .replace("$_TODAY_PLUS_1_$", todayPlus1)
                        .replace("$_TODAY_PLUS_2_$", todayPlus2);
                bw.write(replacedLine + "\n");
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        try {
            Files.copy(backupFile, csvFile, copyOption);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Recommended Posts

String replacement
Java string multiple replacement
String
String puzzle
Java string
Liar String
java.lang Summary 2 (String)
String Buffer practice
[Java] String padding
MyBatis string comparison
Java string processing
String class methods
Split string (Java)
Delete any string