• RandomAccessFile(),读写文件数据的API,以及复制文件操作


    package seday03;
    import java.io.File;
    import java.io.RandomAccessFile;

    import java.io.IOException;

    /**
    *
    * @author xingsir
    *java.io.RandomAccessFile
    * 专门用来读写文件数据的API,其基于指针读写,可以对文件任意位置进行读写操作,编辑文件数据内容非常灵活。
    */
    public class RandomAccessFileDemo {

    public static void main(String[] args) throws IOException {
    /*
    * 创建一个对当前目录下的 test1.txt文件操作的RAF
    *
    * 创建RAF时第一个参数为要操作的文件,第二个参数 为模式,模式有两个比较常用的选项:
    * "r":只读模式
    * "rw":读写模式
    */
    RandomAccessFile raf=new RandomAccessFile("./test1.txt","rw");
    raf.write(1);
    System.out.println("写出完毕!");

    raf.close();

    }

    }

    //===============================================================================

    package seday03;

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

    /**
    * @author xingsir
    * 从文件中读取字节
    */
    public class RandomAccsessFileDemo2 {

    public static void main(String[] args) throws IOException {
    RandomAccessFile raf= new RandomAccessFile("Test1.txt","r");
    /*
    * int read()
    * 从文件中读取1个字节,并以int形式返回
    * 若返回值为-1,则表示已经读取到了文件末尾
    */
    int d = raf.read();
    System.out.println(d);

    d = raf.read();
    System.out.println(d);

    raf.close();
    }

    }

    //================================================================================

    package seday03;

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

    /**
    * @author xingsir
    * RandomAccessFile 复制文件操作
    */
    public class CopyDemo {

    public static void main(String[] args) throws IOException {
    RandomAccessFile src
    = new RandomAccessFile("./test1.txt","r");

    RandomAccessFile desc
    = new RandomAccessFile("./test1_copy.txt","rw");

    int d = 0;
    while((d = src.read())!=-1) {
    desc.write(d);
    }
    System.out.println("复制完毕!");

    src.close();
    desc.close();

    }

    }

  • 相关阅读:
    js中的投掷筛子的小游戏
    js俩习题
    python中socket理论
    python实现计时器(装饰器)
    python之正则表达式(re模块)用法总结
    python练习题之随机生成验证码
    python中模块介绍
    python中的装饰器基本理论
    python类与对象练习题扑克牌
    Java抓取网页数据
  • 原文地址:https://www.cnblogs.com/xingsir/p/11990519.html
Copyright © 2020-2023  润新知