JAVA读取CSV文件内容

JAVA读取CSV文件内容

package test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取CSV文件内容
 */
public class ReadCSV {

    public static void main(String[] args) throws Exception {
        String fileName = "";
        String fileContent = readCSV(fileName);
        System.out.println(fileContent);
    }

    /**
     * 读取CSV文件的静态方法,使用CSV文件的绝对文件路径作为函数参数
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private static String readCSV(String fileName) throws Exception {
        String record;
        StringBuilder sb = new StringBuilder();
        // 设定UTF-8字符集,使用带缓冲区的字符输入流BufferedReader读取文件内容
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8));
        //跳过表头所在的行
        file.readLine();

        // 遍历数据行
        while ((record = file.readLine()) != null) {
            String[] fields = record.split(",");
            for (int i = 0; i < fields.length; i++) {
                sb.append(fields[0]).append("|");
            }
            sb.append("\r\n");
        }
        // 关闭文件
        file.close();
        return sb.toString();
    }
}

你可能感兴趣的:(Java)