Hi,
I am trying to write to a .txt file an integer
but the characters I see when I open the file are strange.

Could you tell me what happens ??

import java.io.*;

public class A
{
   public static int readInt() 
   {
  
       byte b[] = new byte[16]; 
       String str;
       try {
           System.in.read(b);
           str = (new String(b)).trim();
           return Integer.parseInt(str);
        } catch (IOException e) {
            System.out.println("Exception: " + e.toString());
            return 0;
        } catch (NumberFormatException e) {
            System.out.println("Exception: " + e.toString() + "\nReturned value: -1");
            return -1;
        }

  }
    
    
    
    public static void main(String[] args)
    {
        System.out.println("Press Int:");
        int i = readInt();

 
        try {
            FileOutputStream f = new FileOutputStream("test.txt");
            BufferedOutputStream b = new BufferedOutputStream(f);
            DataOutputStream d = new DataOutputStream(b);


            d.writeInt(i);
           
            d.close();
} catch (FileNotFoundException e) {}
catch (IOException e) {}
}
}

Anybody ???

Use BufferedWriter that takes argument a FileWriter. Check their API

DataOutputStream will write the int as bytes to the file, that is why strange symbols are appearing. If you want the int to be displayed as is, you should use an Object like a PrintWriter instead.

DataOutputStream will write the int as bytes to the file, that is why strange symbols are appearing. If you want the int to be displayed as is, you should use an Object like a PrintWriter instead.

Thanks a lot for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.