1

Hi write a java code to write the output into a csv file. This is the sample code:

File downloadPlace = new File(realContextPathFile, "general");
File gtwayDestRateFile = new File(downloadPlace, (new StringBuilder("ConnectionReport")).append(System.currentTimeMillis()).append(".csv").toString());
PrintWriter pw = new PrintWriter(new FileWriter(gtwayDestRateFile));

pw.print("Operator name,");
pw.print("Telephone Number,");
pw.print("Op1");
pw.print("012365479");
pw.print("Op2");
pw.print("09746");
pw.close();
p_response.setContentType("application/octet-stream");
p_response.setHeader("Content-Disposition", (new StringBuilder("attachment; filename=\"")).append(gtwayDestRateFile.getName()).append("\"").toString());
FileInputStream fis = new FileInputStream(gtwayDestRateFile);
byte buf[] = new byte[4096];
ServletOutputStream out = p_response.getOutputStream();
do
{
    int n = fis.read(buf);
    if(n == -1)
       break;
    out.write(buf, 0, n);
} while(true);
fis.close();
out.flush();

In both case the output is like this: 12365479 instead of 012365479
And 9746 instead of 09746
Can anyone tell me how can i solve this problem?

1
  • You should avoid problems like this by using a framework like OpenCSV Commented Jan 4, 2012 at 10:43

3 Answers 3

1

Are you sure that the file is written wrongly, and you're not just opening it in Excel which is interpreting these as numbers and thus losing the leading zeroes? Try opening it in a text editor.

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

1 Comment

No i need to write my output in csv file.And when i try to write this the leading zero is disappeared.
1

If you write to System.out instead you get

Operator name,Telephone Number,Op1012365479Op209746

As you can see the 0 is where you would expect. Perhaps the problem is you don't have , between fields.

If you open such a file using excel it will remove leading 0 as it assume its a number. To avoid this you need to use double quotes around the field so it is treated as text.

Comments

0

Read the file in a text editor, my guess is that it has the zero and what's reading it is thinking it's a number. Try putting quotes round it.

pw.print("\"012365479\"");

1 Comment

if i write String str="012365479" then how can i add this with pw.print("\"012365479\""); ?

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.