码迷,mamicode.com
首页 > 数据库 > 详细

Java 核心编程——文件随机读写类(RandomAccessFile)

时间:2017-08-24 19:58:33      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:打开   核心编程   内容   catch   create   and   auto   long   创建文件   

1.RandomAccessFile

  RandomAccessFile主要用于文件内容的读写访问

2.访问模式

  “r”:只读方式。

  “rw”:打开以便读取和访问,如果文件不存在则创建文件。

  “rws”: 除了‘rw‘功能以外,文件内容或者元数据更新时一同写入。

  “rwd”:除了‘rw‘功能以外,文件内容更新时一同写入。

3.使用案例

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccess {
    
    
    public static void main(String[] args) {
        try {
            File file = new File("C:\\img\\666.txt");
            
            //打开文件
            RandomAccessFile randomAccess = new RandomAccessFile(file,"rwd"); //访问文件 
            Long lenth = randomAccess.length(); //获取文件长度
            System.out.println("lenth:"+lenth);
            randomAccess.seek(4); //设置指针位置
            
            //读取文件
            int c = randomAccess.read(); //读取一个字节
            System.out.println("c:"+c);
            System.out.println("c:"+(char)c); //转换为字符
            
            byte[] b = new byte[3]; //读取字节数字,创建数组
            randomAccess.read(b, 1, 2); //从指针1处读取两个字节写入数组b中
            String s = new String(b); //转换为字符串
            System.out.println("byte:"+s); //输出
            
            //写入文件
            File file2 = new File("C:\\img\\777.txt");
            if(!file2.getParentFile().exists()){
                file2.getParentFile().mkdirs();
            } 
            file2.createNewFile();
            RandomAccessFile randomAccess2 = new RandomAccessFile(file2,"rwd"); //访问文件 
            randomAccess2.write(b); //写入字符数组
            
            //关闭文件
            randomAccess.close();
            randomAccess2.close();
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }

}

 

Java 核心编程——文件随机读写类(RandomAccessFile)

标签:打开   核心编程   内容   catch   create   and   auto   long   创建文件   

原文地址:http://www.cnblogs.com/wwyx-xi/p/7424660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!