Java从文件中读取字节数据的固定套路

来源:互联网 发布:淘宝怎么买weed叶子 编辑:程序博客网 时间:2024/05/17 02:22

从文件中读取字节数据的固定套路(仅方法)

     /**      * 测试从文件中读取字节数据      * @throws IOException       */     @Test     public void readTest() throws IOException {         File file = new File("msg/123123123.txt");         RandomAccessFile raf = new RandomAccessFile(file, "rw");         // 读取单个字节数据的套路         // 一次读取一个字节(8位二进制数)         // 返回:一个字符编码         int code = raf.read();         // 将编码给人看,需要强制类型转换         System.out.println((char)code);         /*连续读取字节数据的固定套路:          *  Step1:定义一个int类型的变量,用于临时存储接住的字节          *  Step2:使用while循环反复调用read方法          *  Step3:循环条件为read方法返回值!=-1*/         int code = -1; // 接受每个读出的字节,翻译成的整数         while((code = raf.read()) != -1) {             System.out.print((char)code);         }        //执行结果:(源文件中内容为 "int a=100")        /* Output:        * int a=100        * /
1 0