简体   繁体   中英

How can I write the “word” representation of an integer to a file in Java?

Here is a sample code:

File x = new File("garbage.byte");
x.createNewFile();

int i1 = 5;

DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(x));
dataOutputStream.write(i1);
dataOutputStream.flush();
dataOutputStream.close();

When I open the file garbage.byte in a hex viewer I will see:

00000101

which is ok.

My question is, what if I have an integer greater than 256?

How can I write 2 bytes into the file which will represent the integer greater than 256?

Use:

dataOutputStream.writeShort(i1);

to write i1 as a short (which is 2 bytes).

Similarly, there is writeInt (4 bytes) and writeLong (8 bytes). DataOutputStream has a method to write each of Java's primitive types.

Use writeInt() method of DataOutputStream . It will fit for an integer. You can use the following code snippet -

   try{   

        fos = new FileOutputStream("c:\\test.txt");        
        dos = new DataOutputStream(fos); 
        dos.writeInt(i1); 

   }catch(Exception e){
       //handle exception
   }finally{
       if(fos!=null)
           fos.close();
       if(dos!=null)
           dos.close();
   }

Hope it will help.
Thanks a lot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM