Java:导入CSV问题,前导零

时间:2019-05-14 13:45:27

标签: java csv

我正在尝试导入csv文件,但是前导零会给我带来麻烦。

CSV的结构:

code1 | code2 | code3
-----------------------
00101 | 00021 | 0589654
00101 | 00022 | 0589654
00101 | 00023 | 0589654
00101 | 00024 | 0589654

这是我的读取CSV代码:

private static List<Code> readCodesFromCSV(String fileName) {
        List<Code> codes = new ArrayList<>();
        Path pathToFile = Paths.get(fileName);

        // create an instance of BufferedReader
        // using try with resource, Java 7 feature to close resources
        try (BufferedReader br = Files.newBufferedReader(pathToFile)) {

            // read the first line from the text file
            String line = br.readLine();

            // loop until all lines are read
            while (line != null) {

                // use string.split to load a string array with the values from
                // each line of
                // the file, using a comma as the delimiter
                String[] attributes = line.split(",");

                Code code = createCode(attributes);

                // adding book into ArrayList
                codes.add(code);

                // read next line before looping
                // if end of file reached, line would be null
                line = br.readLine();
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return codes;
    }

    private static Code createCode(String[] metadata) {
        String code = "\"\t" + metadata[0] + "\"" + "\"\t" + metadata[1] + "\"" + "\"\t" + metadata[2] + "\"";
        //String code = metadata[0] + metadata[1] + metadata[2];;


        // create and return code of this metadata
        return new Code(code);
    }

我需要将所有3个代码合并为1,但是问题是前导零。当我导入文件并获取合并的代码时,我得到的代码没有前导零,因此我尝试添加\ t,但这无济于事。 有谁知道我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

编写一个带有String[]参数的新构造函数,而不是以某种自定义格式将字符串粘合在一起以由当前构造函数进行解析,会不会更简单?

顺便说一句,您的构造函数将使用String进行调用,如下所示:
(我保留了\t不变,所有其他字符都位于String值中...)

"\t00101""\t00021""\t0589654"

答案 1 :(得分:1)

为什么不只将String的Code数据类型替换为String,然后在每行中找到正确的Code List,然后解析或将其转换为所需的内容。

private static List<String> readCodesFromCSV(String fileName) throws IOException {
        List<String> codes = new ArrayList<>();
        Path pathToFile = Paths.get(fileName);

        // create an instance of BufferedReader
        // using try with resource, Java 7 feature to close resources
        try (BufferedReader br = Files.newBufferedReader(pathToFile)) {

            // read the first line from the text file
            String line = br.readLine();

            // loop until all lines are read
            while (line != null) {

                // use string.split to load a string array with the values from
                // each line of
                // the file, using a comma as the delimiter
                String[] attributes = line.split(",");

                String code = createCode(attributes);

                // adding book into ArrayList
                codes.add(code);

                // read next line before looping
                // if end of file reached, line would be null
                line = br.readLine();
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        return codes;
    }

    private static String createCode(String[] metadata) {
        String code = metadata[0] + metadata[1] + metadata[2];
        return code;
    }

答案 2 :(得分:0)

如前所述,从代码中尚不清楚Code构造函数中发生了什么,但是假设存在问题,

  

在将前导零的值解析为某些编号的数据类型时,请检查以下解析String (with leading zero) into int数据类型的示例:

代码是taking String array,其值带有前导零和parsing into String with separator,第二种方法通过Integer.parseInt()解析同一数组into int

public static void testMe() {
    String[] testData = {"00101","00021","0589654","00101","00022"};
    System.out.println("INPUT: ");
    for (int i = 0; i < testData.length; i++) {
        System.out.print(testData[i] + ",");
    }

    System.out.println("\n");
    String stringData = loadStringArrayToString(testData);
    System.out.println("check, its parsed with leading zeros: \n" + stringData +"\n");

    int[] intData = loadStringArrayToIntArray(testData);
    System.out.println("check, zeros are gone (because integer as datatype):");
    for (int i = 0; i < intData.length; i++) {
        System.out.print(intData[i] + ", ");
    }

}


public static String loadStringArrayToString(String[] inputData) {
    StringBuilder sb = new StringBuilder();
    char separator = ';';

    // -1 to avoid last separator
    for (int i = 0; i < inputData.length -1; i++) {
        sb.append(inputData[i]);
        sb.append(separator);
    }
    sb.append(inputData[inputData.length-1]);

    return sb.toString();
}

public static int[] loadStringArrayToIntArray(String[] inData) {
    int[] retData = new int[inData.length];

    for (int i = 0; i < inData.length; i++) {
        retData[i] = Integer.parseInt(inData[i]);
    }

    return retData;
}

输出为:

INPUT: 
00101,00021,0589654,00101,00022,

check, its parsed with leading zeros: 
00101;00021;0589654;00101;00022

check, zeros are gone (because integer as datatype):
101, 21, 589654, 101, 22,