Java 教程

用 Java 将文本文件转为 CSV

在 Java 中用两种方式将文本文件转 CSV:适合简单数据的无依赖 BufferedReader 版本,以及当字段可能包含逗号、引号或换行符时使用 OpenCSV。包括 UTF-8 处理。

分步指南Copy-paste codeFree converter included
广告
概述

Convert text to CSV in Java

In Java you can convert text to CSV with nothing but the standard library when the data is simple, or with a library like OpenCSV when correct quoting matters. Both approaches are below, including how to read and write UTF-8 explicitly.

For a one-off file, the online converter is quicker; the Java code suits back-end services and batch jobs.

Plain Java with BufferedReader

For tab- or space-separated data with no embedded delimiters, split each line and join with commas:

Java — BufferedReader (simple)
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

public class TextToCsv {
    public static void main(String[] args) throws IOException {
        try (BufferedReader r = Files.newBufferedReader(
                 Paths.get("input.txt"), StandardCharsets.UTF_8);
             BufferedWriter w = Files.newBufferedWriter(
                 Paths.get("output.csv"), StandardCharsets.UTF_8)) {
            String line;
            while ((line = r.readLine()) != null) {
                String[] fields = line.split("\t", -1);  // -1 keeps empty fields
                w.write(String.join(",", fields));
                w.newLine();
            }
        }
    }
}

This is fine for clean data, but it does not quote values that contain a comma — use OpenCSV for that.

OpenCSV for correct quoting

Add OpenCSV (Maven: com.opencsv:opencsv). It reads the source with the right separator and writes properly quoted CSV:

Java — OpenCSV
import com.opencsv.*;
import java.io.*;

public class Convert {
    public static void main(String[] args) throws Exception {
        CSVParser parser = new CSVParserBuilder().withSeparator('\t').build();
        try (CSVReader reader = new CSVReaderBuilder(new FileReader("input.txt"))
                 .withCSVParser(parser).build();
             CSVWriter writer = new CSVWriter(new FileWriter("output.csv"))) {
            String[] row;
            while ((row = reader.readNext()) != null) {
                writer.writeNext(row);   // quotes fields automatically
            }
        }
    }
}

OpenCSV handles embedded commas, quotes and newlines, so the output re-imports cleanly everywhere.

Encoding and batch files

Always specify the charset when reading and writing, as shown above with StandardCharsets.UTF_8, to avoid platform-default surprises. To convert a directory, list the files and run the same logic per file:

Java — convert every .txt in a folder
import java.nio.file.*;
import java.util.stream.*;

try (Stream<Path> files = Files.list(Paths.get("."))) {
    files.filter(p -> p.toString().endsWith(".txt")).forEach(p -> {
        // call your convert(p, outputPath) method here
    });
}
Good to know

Robustness tips for Java

The dependency-free approach is fine for trusted, simple input, but production code should assume data is messy. Splitting on a delimiter with String.split silently mishandles quoted fields that contain the delimiter or a newline — OpenCSV (or Apache Commons CSV) exists precisely to get those cases right, so prefer it whenever the source is not fully under your control.

Always specify the charset explicitly with StandardCharsets.UTF_8; relying on the platform default makes the same code behave differently on different machines. Remember to pass -1 as the limit to String.split if you need to preserve trailing empty fields, which the default drops. For very large files, stream line by line with a BufferedReader rather than reading the whole file into memory, and flush and close writers in a try-with-resources block so no data is lost on an exception. A quick verification is to re-read the generated CSV with the same library and assert the column count matches your expectation.

If your data maps to a fixed structure, OpenCSV can bind rows directly to Java beans with CsvToBeanBuilder, and write beans back out, which is cleaner than handling raw String[] arrays. Add the dependency through Maven or Gradle so the library and its version are managed for you rather than dropping a jar on the classpath by hand.

In short, use OpenCSV for any data that is not fully under your control, specify UTF-8 explicitly, and stream large files rather than loading them whole. With those habits, a few lines of Java convert text to CSV reliably as part of any service or batch job.

常见问题

Convert Text File to CSV in Java — FAQ

How do I convert text to CSV in Java?

Read lines with a BufferedReader and write comma-joined output, or use OpenCSV for automatic quoting.

Which CSV library should I use?

OpenCSV or Apache Commons CSV; both handle quoting and embedded newlines correctly.

How do I handle UTF-8?

Pass StandardCharsets.UTF_8 to the reader and writer.

How do I keep empty fields?

Use line.split("\t", -1) — the -1 limit preserves trailing empty values.