java文件读写时int类型问题

很多时候我们需要从文件中读取数据,而当数据是整型的时候,需要格外的小心,因为你会发现你读入或者写进的都是一串不相关的数,并不是原本要写的。例如

    public static void output() {
        File out=new File("output.txt");
        try {
            BufferedWriter bw=new BufferedWriter(new FileWriter(out));
            bw.write(12);
            bw.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

结果如下图
与我想写进的完全不是一个东西
可能是BufferedWriter 并不适合写 int,换个DataOutputStream试下

    public static void output() {
        File out=new File("output.txt");
        try {
//          BufferedWriter bw=new BufferedWriter(new FileWriter(out));
//          String result=Integer.toString(core());
//          bw.write(result);
//          
//          bw.close();
            DataOutputStream dos=new DataOutputStream(new    FileOutputStream(out));
            dos.writeInt(321);
            dos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

这里写图片描述
本来想写个321 没想到却是变成了乱码。

而读入的时候也类似。找了一下DataOutputStream.writeInt()的注释

Writes an int to the underlying output stream as four bytes, high byte first. If no exception is thrown, the counter written incremented by 4

大意是 :向输出流写入4个字节,高位字节先写入。如果没有异常,计数器+4

这里计数器+4,指在文件中的指针+4,移动4个字节。321的16进制为 141。二进制为
0001 0100 0001,补足4个字节为
0000 0000 0000 0000 0000 0001 0100 0001 =》化为10进制 0 0 1 65
windows记事本中的编码默认是ANSI,即ASCii码表示。所以表现为 空格 空格 框 A

而BufferedWriter.write(int )是这样写的

int specifying a character to be written

大意是 :int作为一个字符写入
12的asc ii码 就是那个箭头。

而读入和写相差不大。所以就不赘述了。
不知道大家有没有遇到相同或者类似的问题呢,欢迎留言哦。

扫描二维码关注公众号,回复: 356113 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_36254754/article/details/79892041