【问题标题】:Write String with preceding zeros into CSV file in java将带有前面零的字符串写入Java中的CSV文件
【发布时间】:2018-06-26 13:18:32
【问题描述】:

我正在尝试将帐号(例如:00000900123)写入 java 中的 csv 文件。创建文件并写入帐号后,帐号会自动转换为 900123。我如何编码以使其在文件中保留前面的零。

public class WriteData {

public static void main(String[] args) {

    BufferedWriter bufferedWriter = null;
    FileOutputStream fileOutputStream = null;
    String header = "name, accountNumber, amount";
    String record = "savings, 000090123, 12000.0";

    File file = new File("testfile.csv");
    try {

        fileOutputStream = new FileOutputStream(file);
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

        bufferedWriter.write(header);
        bufferedWriter.newLine();
        bufferedWriter.write(record);
        bufferedWriter.newLine();

    } catch(FileNotFoundException fne) {
    } catch(IOException ioe) {
    } finally {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
            }
        }

        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

 }

运行上述程序后,它会生成一个 testfile.csv。如果我在文本编辑器中打开它,它会显示如下的完整字符串,

name, accountNumber, amount
savings, 000090123, 12000.0

但如果我在 csv 中打开,帐号将是 90123。我们需要将 csv 文件提供给客户,因此需要完整的帐号。

【问题讨论】:

  • 向我们展示代码,我们会告诉您。
  • 您能否确定前导零是由您用于读取 CSV 的软件在显示时被剥离,还是在您的 Java 代码写入时被剥离? (我建议您使用文本编辑器打开 .csv 文件以确保)
  • 顺便说一句。虽然“帐号”被称为“数字”,但最好不要将它们视为数字,而是将它们视为字符串。例如,“国际银行帐号”(IBAN)实际上也包含字母。
  • 我已经添加了上面的代码。

标签: java string file


【解决方案1】:

我希望您使用 Excel 打开 CSV,我建议您使用 excel 并按照这些instructions 来获取您需要的内容。 希望这会有所帮助,一旦您导入数据,保存文件并与用户共享。

【讨论】:

    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 2016-06-15
    • 2016-10-22
    • 2014-04-18
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    相关资源
    最近更新 更多