简体   繁体   English

如何在Java中将整数的“单词”表示形式写入文件?

[英]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: 在十六进制查看器中打开文件garbage.byte时 ,我将看到:

00000101

which is ok. 没关系

My question is, what if I have an integer greater than 256? 我的问题是,如果我的整数大于256,该怎么办?

How can I write 2 bytes into the file which will represent the integer greater than 256? 如何将2个字节写入表示大于256的整数的文件中?

Use: 采用:

dataOutputStream.writeShort(i1);

to write i1 as a short (which is 2 bytes). 将i1写为short (2字节)。

Similarly, there is writeInt (4 bytes) and writeLong (8 bytes). 同样,有writeInt (4个字节)和writeLong (8个字节)。 DataOutputStream has a method to write each of Java's primitive types. DataOutputStream有一种方法可以编写每种Java基本类型。

Use writeInt() method of DataOutputStream . 使用DataOutputStream的 writeInt()方法。 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 非常感谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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