-6

I am trying to write account numbers(e.g: 00000900123) into csv file in java. After creating a file and writing account number gets converted into 900123 automatically. How can i code to make it retain the preceding zeros in the file.

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) {
            }
        }
    }
}

 }

After i run the above program it generates a testfile.csv. If i open it in text editor it shows the full string as below,

name, accountNumber, amount
savings, 000090123, 12000.0

But if i open in csv account number would be 90123. We need to provide the csv file to client so complete account number is required.

6
  • Show us the code and we'll tell you. Commented Jan 17, 2018 at 15:42
  • 1
    Possible duplicate of Format an Integer using Java String Format Commented Jan 17, 2018 at 15:43
  • Can you identify whether the leading zeroes are stripped at display by the software you're using to read CSVs, or at write-time by your java code? (I suggest you open the .csv file with a text editor to make sure) Commented Jan 17, 2018 at 15:43
  • 3
    Btw. While "account numbers" are called "numbers" it would probably be best to not treat them as numbers but Strings instead. The "International Bank Account Number" (IBAN) for example actually also contains letters. Commented Jan 17, 2018 at 15:43
  • 1
    I have added the code above. Commented Jan 17, 2018 at 15:52

1 Answer 1

-2

I am hoping that you are using Excel to open the CSV, I would recommend using excel and following these instructions to get what you need. Hope this helps, once you have the data imported save the file and share it with the users.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.