View Javadoc
1   package integrationTest.SR121;
2   
3   import com.opencsv.CSVParser;
4   import com.opencsv.CSVParserBuilder;
5   import com.opencsv.CSVReader;
6   import com.opencsv.CSVReaderBuilder;
7   import com.opencsv.exceptions.CsvException;
8   import org.junit.jupiter.api.Test;
9   
10  import java.io.File;
11  import java.io.FileReader;
12  import java.io.FileWriter;
13  import java.io.IOException;
14  import java.util.List;
15  
16  public class SR121Test {
17  
18      @Test
19      public void newlineEscapeCharacterIssue() {
20          // Create a File object with the name of the text file to create.
21          File csvFilePath = new File("my_text_file_with_content.txt");
22          csvFilePath.deleteOnExit();
23  
24  // Try to create the file. If the file already exists, it will be overwritten.
25          try (FileWriter writer = new FileWriter(csvFilePath)) {
26              // Write the text to the file.
27              writer.write("\"ID\"|\"TYPE\"|\"PROFILE\"");
28              writer.write("\n");
29              writer.write("\"123\"|\"MISC\"|\"Profile ABC\"");
30              writer.write("\n");
31              writer.write("\"456\"|\"MISC\"|\"Profile DEF\\n& Profile GHI\"");
32              writer.write("\n");
33              writer.write("\"789\"|\"MISC\"|\"Profile \\\"JKL\\\"\"");
34              writer.write("\n");
35          } catch (IOException e) {
36              System.out.println("An error occurred while trying to create the file: " + e.getMessage());
37          }
38  
39  // Print a message indicating that the file was created successfully.
40          System.out.println("The file was created successfully!");
41  
42          CSVParser csvParser = new CSVParserBuilder()
43                  .withSeparator('|')
44                  .withQuoteChar('\"')
45                  .withEscapeChar(CSVParser.DEFAULT_ESCAPE_CHARACTER)
46                  .withIgnoreQuotations(false)
47                  .build();
48  
49          try (CSVReader csvReader = new CSVReaderBuilder(new FileReader(csvFilePath.getPath())).withCSVParser(csvParser).build()) {
50              // Read all lines from the CSV file
51              List<String[]> allLines = csvReader.readAll();
52  
53              // Iterate over the lines and print them to the console
54              for (String[] line : allLines) {
55                  for (String column : line) {
56                      System.out.print(column + "\t");
57                  }
58                  System.out.println();
59              }
60  
61              // Close the CSV reader
62              csvReader.close();
63          } catch (IOException | CsvException e) {
64              System.out.println("An error occurred while trying to open the file: " + e.getMessage());
65          }
66      }
67  }