如何在csv中显示像00019这样的字符串

时间:2017-05-24 08:37:26

标签: java csv

我在我的csv中输入了一些结果如下:

ID            COUNTRY
0009             FR
0006             FR

问题是当我打开我的文件.CSV时,我在ID下读取值9和6而不是0009和0006.它是如何可能的以及如何避免这个问题?有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以将值转义为字符串

ID            COUNTRY 
"0009"             FR 
"0006"             FR

我相信你的问题与Java无关,我假设你正在使用标签处理器(Excel,Calc,...)。打开文件时,您必须将列类型显式设置为文本,否则它将“猜测”它是一个数字并清除前导零。

答案 1 :(得分:0)

(鉴于问题是用Java标记的。)

如果你有一个提到的CSV,它是以制表符分隔的:

ID      COUNTRY
0009    FR
0006    FR

假设它位于:src/com/stackoverflow/myfile.csv

您可以阅读如下:

package com.stackoverflow;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CsvReader {

    public static final String CSVFILE = "src/com/stackoverflow/myfile.csv";

    public static void main(String[] args) {

        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = "\\t+"; // use tab as separator

        try {    
            br = new BufferedReader(new FileReader(CSVFILE));
            while ((line = br.readLine()) != null) {

                String[] info = line.split(cvsSplitBy);

                StringBuilder details = new StringBuilder();
                details.append("ID = ");
                details.append(info[0]);
                details.append(", Country = ");
                details.append(info[1]);

                System.out.println(details.toString());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

输出结果为:

ID = ID, Country = COUNTRY
ID = 0009, Country = FR
ID = 0006, Country = FR

注意:它是0009和0006

更新(只读Java 8方式读取CSV文件):

package com.stackoverflow;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class CsvReader {

    public static final String CSVFILE = "src/com/stackoverflow/myfile.csv";

    public static void main(String[] args) {

        String cvsSplitBy = "\\t+"; // use tab as separator

        try (Stream<String> stream = Files.lines(Paths.get(CSVFILE))) {

            stream.forEach(line -> {
                String[] info = line.split(cvsSplitBy);

                StringBuilder details = new StringBuilder();
                details.append("ID = ");
                details.append(info[0]);
                details.append(", Country = ");
                details.append(info[1]);

                System.out.println(details.toString());
            });

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

}