Read CSV with Scanner()
When reading CSV files using Java, it's possible to encounter issues with text containing spaces being moved to new lines. This occurs when the Scanner class interprets spaces as delimiters.
To address this problem, it's recommended to avoid using Scanner() for CSV parsing. Instead, it's best to utilize libraries specifically designed for CSV handling, such as:
These libraries properly account for the complexities of CSV parsing, including the presence of spaces, quotes, and escaping characters.
Here's an example using the opencsv library:
<code class="java">import com.opencsv.CSVReader; import java.io.FileReader; import java.util.List; public class Main { public static void main(String[] args) { String fileName = "uploadedcsv/employees.csv"; try (CSVReader reader = new CSVReader(new FileReader(fileName))) { List<String[]> lines = reader.readAll(); for (String[] line : lines) { for (String value : line) { System.out.print(value + " "); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } }</code>
By employing a specialized CSV parsing library, you can accurately handle text with spaces and ensure that the data is parsed correctly.
The above is the detailed content of Can I Parse CSV with Scanner() and Handle Spaces Accurately?. For more information, please follow other related articles on the PHP Chinese website!