zoukankan      html  css  js  c++  java
  • 在文件指定位置读取和写入内容RandomAccessFile

    import java.io.IOException;
    import java.io.RandomAccessFile;

    /**
     * RandomAccessFile是属于随机读取类,是可以对文件本身的内容直接随机进行操作的,就是说可以指定位置
     * 的读取和写入内容
     * @author andy
     *
     */
    public class RandomAccessFileTest {

        public static void main(String args[]) throws IOException {
            write();
            read();
        }
        
        public static void write() throws IOException {
            //以读写的方式来访问该文件
            RandomAccessFile raf = new RandomAccessFile("D:\test.txt", "rw");
            raf.writeBytes("Hello World!");
            raf.writeBoolean(true);
            raf.writeInt(30);
            raf.writeDouble(3.56);
            raf.close();
        }
        
        public static void read() throws IOException {
            RandomAccessFile raf = new RandomAccessFile("D:\test.txt", "r");
            raf.seek(12);//设置指针的位置
            boolean booleanValue = raf.readBoolean();
            int intValue = raf.readInt();
            double doubleValue = raf.readDouble();
            raf.seek(0);//设置指针的位置为文件的开始部分
            byte[] bytes = new byte[12];
            for (int i=0; i<bytes.length; i++)
                bytes[i] = raf.readByte();//每次读一个字节,并把它赋值给字节bytes[i]
            String stringValue = new String(bytes);
            raf.skipBytes(1);//指针跳过一个字节
            int intValue2 = raf.readInt();
            raf.close();
            System.out.println(booleanValue);
            System.out.println(intValue);
            System.out.println(doubleValue);
            System.out.println(stringValue);
            System.out.println(intValue2);
        }
        
    }
    转自:http://haohaoxuexi.iteye.com/blog/1235317

  • 相关阅读:
    Winform中在ZedGraph中最多可以添加多少条曲线(转)
    c#委托的含义和用法
    vs2010打开vs2017工程
    C# Socket编程资源
    C# 调用打印机 打印 Excel (转)
    NPOI 教程
    C# 调用C++ DLL 的类型转换(转载版)(转)
    进程间通信(网络阅读笔记)
    NPOI 第二篇 设置样式与合并单元格(转)
    分布式事务的 6 种解决方案,写得非常好!
  • 原文地址:https://www.cnblogs.com/wushuishui/p/5765518.html
Copyright © 2011-2022 走看看