I/O编程-File类和RandomAccessFile类
来源:互联网 发布:预决算软件有哪些 编辑:程序博客网 时间:2024/06/04 18:09
File类,可以创建文件(包括各种格式)、删除文件;
File file=new File("D:\\workspace\\Test\\1.pdf");if(file.exists())//文件是否存在file.delete();else file.createNewFile();System.out.println("filename:"+file.getName());System.out.println("filepath:"+file.getPath());System.out.println("fileabspath:"+file.getAbsolutePath());//绝对路径System.out.println("fileread?:"+file.canRead());//是否可读System.out.println("filewrite?:"+file.canWrite());//是否可写System.out.println("filemofifytime:"+new Date(file.lastModified()));System.out.println("filedirectory:"+file.isDirectory());//是否是一个目录System.out.println("parentfile:"+file.getParentFile());RandomAccessFile类用于随机的读取文件,也就是可以不从文件的开始位置访问文件,可以从我们指定文件任意位置开始读取,不如说客户端从服务器下载文件时的断点下载等等;另外在读取等长记录格式的文件时更有优势,不如说数据库里的一条条记录;如下面的程序实例,是向文件中写入一个三条数据,然后不按照顺序读取:
public static void main(String[] args) throws IOException {emploee e1=new emploee("aaaaaaaa", 333);emploee e2=new emploee("bbbbbbbb", 2);emploee e3=new emploee("cccccccc", 3);RandomAccessFile w=new RandomAccessFile("2.txt", "rw");//如果姓名是中文使用writechar方法写入//如果姓名是英文w.write(e1.getName().getBytes());/* * 这个地方应该使用writeInt方法把int类型的数据按照4个字节写入文件 同样使用readInt读取 * 如果使用write()写入使用read读取,则结果为333-256=77岁;*/w.writeInt(e1.getAge());w.write(e2.getName().getBytes());w.writeInt(e2.getAge());w.write(e3.getName().getBytes());w.writeInt(e3.getAge());w.close();RandomAccessFile r=new RandomAccessFile("2.txt", "r");int len=0;String name=null;byte buff[]=new byte[emploee.len];r.skipBytes(emploee.len+4);//跳转到第九个字节len=r.read(buff);//得出实际读到 的长度name=new String(buff,0,len);System.out.println(name+" "+r.readInt());r.seek(0);//定位到0位置len=r.read(buff);name=new String(buff,0,len);System.out.println(name+" "+r.readInt());r.skipBytes(emploee.len+4);len=r.read(buff);name=new String(buff,0,len);System.out.println(name+" "+r.readInt());}}//定义员工类class emploee{public String getName() {return name;}public int getAge() {return age;}private String name;private int age;static final int len=8;//定义姓名长度,以便于以后程序的升级public emploee(String name, int age) {if(name.length()>len)//保证姓名长度是指定的长度lenname=name.substring(0, len);else {while(name.length()<len)name=name+"\u0000";}this.name = name;this.age = age;}}
- I/O编程-File类和RandomAccessFile类
- JavaSE I/O RandomAccessFile类
- java I/O系统(4)-RandomAccessFile类
- I/O----File类
- File类和RandomAccessFile类
- I/O流,File类
- I/O流--File类
- I/O 输入与输出(2) -- RandomAccessFile类
- 说说 Java I/O 系统之 RandomAccessFile 类
- File和I/O
- File和I/o流
- java i/o 类之File
- java i/o 类之File
- [Java I/O系统]File类
- java中I/O中的File类
- I/O File类创建文件夹
- JAVA I/O(一) File类
- java I/O流-File类
- db2上新建表空间和数据库
- 如何在 Ubuntu 上安装和使用 DropBox
- 双机冷备一不小心出了问题
- OGRE的良好架构
- .Net设计模式之适配器模式(Adapter Pattern)
- I/O编程-File类和RandomAccessFile类
- FPGA学习之路
- Android开发notification跳转
- IOS 网络解析(XML,JSON)
- 第15周项目2
- usaco Barn Repair 解题报告
- 具备全程事务控制的JDBC连接管理器
- 进程间通信编程--管道
- Linux静态库与动态库详解(一看就懂)