Int into String and then back

Please, I need your help...

How to convert Integer into String in a way that the result will be look like this....

Int (5) => String "0005", Int (123) => String "0123" ?

and back operation...

String "0005" => Int "5",String "0123" => Int (123).

Actually, I try to save integer array into a file, and I want that every number will be present by 4 digits. Then, I need to catch these values from a file and convert them back into the integer type.

[510 byte] By [Neludoffa] at [2007-11-27 5:34:34]
# 1
String str=String.format("%5d",123);int i=Integer.parseInt(str);
typeHa at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 2

try this example:

import java.text.*;

public class MyNumber

{

public static void main(String[] s)

{

DecimalFormat df = new DecimalFormat("0000");

System.out.println(df.format(15));

}

}

NourElsaftya at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 3

I tried in the following way, but it doesn't work, there is nothing in an output file

import java.io.*;

import java.text.*;

public class Mynumber

{

public static void main(String[] s)

{

try {

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("integer_into_string.txt")));

DecimalFormat df = new DecimalFormat("0000");

for (int i = 0; i<12 ;i++)

out.print(df.format(i) + " ");

}

catch (IOException e) {}

}

}

How to fixed it?

Neludoffa at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 4
You have to close the file that you open.
jsalonena at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 5
Oh, thank you! It's so stupid mistake =)
Neludoffa at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 6
Aren't you the same person who wanted to save a big matrix in a file?You might want to use a binary file instead of a text file.. http://java.sun.com/docs/books/tutorial/essential/io/datastreams.html
jsalonena at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 7
> Oh, thank you! It's so stupid mistake =)Not stupid, just common :)
jsalonena at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 8

But while we're on the subject of stupidity... catch (IOException e) {}

Never, EVER do that. If the API forces you to catch an exception, at the very least you should print the stack trace: catch (IOException e) {

e.printStackTrace();

}

As you gain more experience you'll get a better feel for dealing with exceptions appropriately, but this is not negotiable: never just swallow exceptions.

(Just kidding about the stupidity, by the way; this too is a common beginner's mistake.)

uncle_alicea at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...
# 9
To jsalonen: I am. Ok, I'll try to understand how it worksTo uncle_alice : thank u. I've got it.
Neludoffa at 2007-7-12 15:02:46 > top of Java-index,Java Essentials,New To Java...