开发者

Determining and printing file size in Java

The method below returns file size as 2. Since it is long, I'm assuming the file size java calculates is 2*64 bits. But actually I saved a 32 bit int + a 16 bit char = 48 bits. Why does Java do this conversion? Also, does Java implicitly store everything as long in the file no matter if char or int ? How do I get the accurate size of 48 bits ?

public static void main(String[] args)
        {
   开发者_运维技巧         File f = new File("C:/sam.txt");
            int a= 42;
            char c= '.';
            try {
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();  
                }
                PrintWriter pw = new PrintWriter(f);
                pw.write(a);
                pw.write(c);
                pw.close();
                System.out.println("file size:"+f.length());
            } catch (FileNotFoundException e) {
                e.printStackTrace();  
            }

        }


No. You wrote two characters. Writers are used for textual data, not for binary data. The documentation of write(int) says:

Writes a single character.

Since the default character encoding of your platform stores those two characters as a single byte (each), the file length is 2 (2 bytes: the length of a file is measured in bytes, as the documentation says). Open the file with a text editor, and see what's in there.

The Java API doc is really useful to know what a class or method does. You should read it.


both calls to write are writing a char, which is 16 bits in memory, but since

new PrintWriter(f)

uses the default character set encoding (probably ASCII or UTF-8 on your system), it results in 2 bytes being written.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜