java 读取CSV文件并输出至txt文件
时间: 2023-07-18 21:24:19 浏览: 48
好的,我可以为您提供 Java 读取 CSV 文件并输出至 txt 文件的代码示例。请参考以下代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CSVtoTXTConverter {
public static void main(String[] args) {
String csvFilePath = "path/to/your/csv/file.csv";
String txtFilePath = "path/to/your/txt/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
FileWriter fw = new FileWriter(txtFilePath)) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append(value.trim()).append(" ");
}
sb.append("\n");
fw.write(sb.toString());
}
System.out.println("Successfully converted CSV to TXT.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
您需要将 `csvFilePath` 和 `txtFilePath` 替换为您实际的文件路径。这个程序将逐行读取 CSV 文件,将每一行拆分成单独的值,然后将其写入 TXT 文件。每个值之间用空格分隔,每行末尾加上换行符。