关于文件读写使用RandomAccessFile类的一些简单操作

本文探讨了在Java中进行文件操作时,如何使用RandomAccessFile类进行文件生成、内容写入等任务。文章提到了File类的基础操作,并指出Files类是File类的扩展,提供更丰富的文件操作静态方法。同时,介绍了Path接口及其在多线程环境中的应用。重点讲解了RandomAccessFile类的优势,如能覆盖文件指定位置内容和追加内容。
摘要由CSDN通过智能技术生成

最近接触到了一些关于文件生成以及文件内容写入的工作任务,关于文件的一些方法常用的是 java.io.File包中的一些方法。这些方法是在java1.0的时候提供的。然后在File类的注释中看到了这个包java.nio.file.Files;随后查看了一下这个包。简单了解了一下

File

/**
 * An abstract representation of file and directory pathnames.
 .......
* <h3>Interoperability with {@code java.nio.file} package</h3>
 *
 * <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>
 * package defines interfaces and classes for the Java virtual machine to access
 * files, file attributes, and file systems. This API may be used to overcome
 * many of the limitations of the {@code java.io.File} class.
 * The {@link #toPath toPath} method may be used to obtain a {@link
 * Path} that uses the abstract path represented by a {@code File} object to
 * locate a file. The resulting {@code Path} may be used with the {@link
 * java.nio.file.Files} class to provide more efficient and extensive access to
 * additional file operations, file attributes, and I/O exceptions to help
 * diagnose errors when an operation on a file fails.
 *
 * @author  unascribed
 * @since   JDK1.0
 */

public class File
    implements Serializable, Comparable<File>
{
	.....
}

从这段注释的说明中可以看出Files类是对原File类的一些操作的扩展。

Files

/**
 * This class consists exclusively of static methods that operate on files,
 * directories, or other types of files.
 *
 * <p> In most cases, the methods defined here will delegate to the associated
 * file system provider to perform the file operations.
 *
 * @since 1.7
 */

public final class Files {
    private Files() { }
    
....
}

这个包是nio下的关于文件操作的一系列类似于工具包的类。这个类中只包含了对文件,目录和其他类型的文件操作的静态方法。

查了 一下关于这个类的使用是与java.nio.file.Path一起使用的。

关于Path类是可以使用在多线程的情况下。

/**
 * An object that may be used to locate a file in a file system. It will
 * typically represent a system dependent file path.
 .....
  * <h2>Concurrency</h2>
 * <p> Implementations of this interface are immutable and safe for use by
 * multiple concurrent threads.
 *
 * @since 1.7
 * @see Paths
 */
public interface Path
    extends Comparable<Path>, Iterable<Path>, Watchable
{
    /**
     * Returns the file system that created this object.
     *
     * @return  the file system that created this object
     */
    FileSystem getFileSystem();
	.....
}

Path是一个接口,有2个实现类。

AbstractPath、ZipPath;

File的基本操作创建文件

/**
 * 指定路径下打开文件,如果文件不存在就创建一个文件
 */
File file = new File("F:\\test\\", "generatorFile.txt");
        if (!file.exists()) {
            try {
                if (!file.createNewFile()) {
                    System.out.println("文件创建失败,或者已经存在");
                }
            } catch (IOException e) {
                System.out.println(e);
                return;
            }
        }
----------------------------------

关于文件内容处理,在网上找到了一个randomAccessFile类,可以在文件中覆盖指定位置的内容,也可以在尾部追加内容。

比较方便的一个文件操作类。

RandomAccessFile randomAccessFile = null;
        try {
            //对rw是文件操作的操作模式
            randomAccessFile = new RandomAccessFile(file, "rw");
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
        }
        randomAccessFile.seek(randomAccessFile.length());
        randomAccessFile.write("abcdcd".getBytes());
        randomAccessFile.close();
操作符号介绍
r以只读的方式打开文本,不能用write方法写入数据
rw允许对文件进行读写操作
rws写操作的时候,同步的刷新到磁盘,刷新内容和元数据
rwd写操作操作,同步的刷新到磁盘,刷新内容
/**
....
* @param      file   the file object
     * @param      mode   the access mode, as described
     *                    <a href="#mode">above</a>
     * @exception  IllegalArgumentException  if the mode argument is not equal
     *               to one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or
     *               <tt>"rwd"</tt>
     * @exception FileNotFoundException
     *            if the mode is <tt>"r"</tt> but the given file object does
     *            not denote an existing regular file, or if the mode begins
     *            with <tt>"rw"</tt> but the given file object does not denote
     *            an existing, writable regular file and a new regular file of
     *            that name cannot be created, or if some other error occurs
     *            while opening or creating the file
     * @exception  SecurityException         if a security manager exists and its
     *               {@code checkRead} method denies read access to the file
     *               or the mode is "rw" and the security manager's
     *               {@code checkWrite} method denies write access to the file
     * @see        java.lang.SecurityManager#checkRead(java.lang.String)
     * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
     * @see        java.nio.channels.FileChannel#force(boolean)
     * @revised 1.4
     * @spec JSR-51
     */
    public RandomAccessFile(File file, String mode)
        throws FileNotFoundException
    {
     ...
    }

RandomAccessFile类的几个常用方法

seek()指定文件的光标位置,你的光标位置,就是下次读文件数据的时候从该位置读取,写入的数据也是从这个位置写,但是写入的数据会覆盖之前的数据
getFilePointer()返回当前文件的偏移量,以字节为单位。也就是文件内容光标的长度。
length()获取文件内容的长度,以字节为单位
read()有多个read()的重载方法可以获取指定长度的数据
write()可以read()方法相反,可以在文件中写入指定长度的数据。
   /**
     * Returns the current offset in this file.
     *
     * @return     the offset from the beginning of the file, in bytes,
     *             at which the next read or write occurs.
     * @exception  IOException  if an I/O error occurs.
     */
    public native long getFilePointer() throws IOException;

Example:
randomAccessFile.seek(3);      
System.out.println(randomAccessFile.getFilePointer());
返回输出3;
------------------------------
    RandomAccessFile randomAccessFile;
        try {
            randomAccessFile = new RandomAccessFile(file, "rws");
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
            return;
        }
//将光标指向文件的开头,写入数据
        randomAccessFile.seek(0);
        randomAccessFile.write("abcde".getBytes());
        randomAccessFile.close();
//在文件后面追加内容
 RandomAccessFile randomAccessFile;
        try {
            randomAccessFile = new RandomAccessFile(file, "rws");
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
            return;
        }

        randomAccessFile.seek(randomAccessFile.length());
        randomAccessFile.write("追加内容abcde".getBytes());
        randomAccessFile.close();
//读取文件内容

        byte[] bytes = new byte[1024];
//从文件开头读取
        randomAccessFile.seek(0);
        while (randomAccessFile.read(bytes) > 0) {
            System.out.println(new String(bytes, 0, bytes.length));
        }
        randomAccessFile.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值