Home > Java > javaTutorial > body text

Can I Parse CSV with Scanner() and Handle Spaces Accurately?

Linda Hamilton
Release: 2024-10-24 18:34:02
Original
601 people have browsed it

Can I Parse CSV with Scanner() and Handle Spaces Accurately?

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:

  • opencsv
  • Ostermiller Java Utilities
  • Apache Commons CSV

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!