Java RandomAccessFile示例

Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.

Java RandomAccessFile提供了将数据读取和写入文件的功能。 RandomAccessFile与文件一起使用,作为存储在文件系统中的大字节数组以及一个游标,通过该游标我们可以移动文件指针的位置。

Java RandomAccessFile (Java RandomAccessFile)

Java RandomAccessFile, RandomAccessFile in java, Java RandomAccessFile read write append example

RandomAccessFile class is part of Java IO. While creating the instance of RandomAccessFile in java, we need to provide the mode to open the file. For example, to open the file for read only mode we have to use “r” and for read-write operations we have to use “rw”.


RandomAccessFile类是Java IO的一部分。 在Java中创建RandomAccessFile实例时,我们需要提供打开文件的模式。 例如,要以只读模式打开文件,我们必须使用“ r”,而对于读写操作,我们必须使用“ rw”。

Using file pointer, we can read or write data from random access file at any position. To get the current file pointer, you can call getFilePointer() method and to set the file pointer index, you can call seek(int i) method.

使用文件指针,我们可以在任何位置从随机访问文件读取或写入数据。 若要获取当前文件指针,可以调用getFilePointer()方法,并可以设置seek(int i)方法来设置文件指针索引。

If we write data at any index where data is already present, it will override it.

如果我们在已经存在数据的任何索引处写入数据,它将覆盖它。

Java RandomAccessFile阅读示例 (Java RandomAccessFile read example)

We can read byte array from a file using RandomAccessFile in java. Below is the pseudo code to read file using RandomAccessFile.

我们可以使用Java中的RandomAccessFile从文件读取字节数组。 下面是使用RandomAccessFile 读取文件的伪代码。

RandomAccessFile raf = new RandomAccessFile("file.txt", "r");
raf.seek(1);
byte[] bytes = new byte[5];
raf.read(bytes);
raf.close();
System.out.println(new String(bytes));

In the first line, we are creating RandomAccessFile instance for the file in read-only mode.

在第一行中,我们将以只读模式为文件创建RandomAccessFile实例。

Then in the second line, we are moving the file pointer to index 1.

然后在第二行中,将文件指针移动到索引1。

We have created a byte array of length 5, so when we are calling read(bytes) method, then 5 bytes are read from file to the byte array.

我们创建了一个长度为5的字节数组,因此,当我们调用read(bytes)方法时,会将5个字节从文件读取到字节数组。

Finally, we are closing the RandomAccessFile resource and printing the byte array to console.

最后,我们将关闭RandomAccessFile资源,并将字节数组打印到控制台。

Java RandomAccessFile编写示例 (Java RandomAccessFile write example)

Here is a simple example showing how to write data to a file using RandomAccessFile in java.

这是一个简单的示例,显示了如何使用Java中的RandomAccessFile将数据写入文件。

RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(5);
raf.write("Data".getBytes());
raf.close();

Since RandomAccessFile treats the file as a byte array, write operation can override the data as well as it can append to a file. It all depends on the file pointer position. If the pointer is moved beyond the file length and then write operation is called, then there will be junk data written in the file. So you should take care of this while using write operation.

由于RandomAccessFile将文件视为字节数组,因此写操作可以覆盖数据以及可以附加到文件。 这完全取决于文件指针的位置。 如果将指针移到文件长度之外,然后调用写操作,则文件中将写入垃圾数据。 因此,在使用写操作时应注意这一点。

RandomAccessFile附加示例 (RandomAccessFile append example)

All we need is to make sure file pointer is at the end of the file to append to a file. Below is the code for append to file using RandomAccessFile.

我们需要做的就是确保文件指针位于文件末尾以追加到文件中。 以下是使用RandomAccessFile追加到文件的代码。

RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(raf.length());
raf.write("Data".getBytes());
raf.close();

Java RandomAccessFile示例 (Java RandomAccessFile Example)

Here is a complete java RandomAccessFile example with different read and write operations.

这是具有不同读写操作的完整Java RandomAccessFile示例。

package com.journaldev.files;

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

public class RandomAccessFileExample {

	public static void main(String[] args) {
		try {
			// file content is "ABCDEFGH"
			String filePath = "/Users/pankaj/Downloads/source.txt"; 
			
			System.out.println(new String(readCharsFromFile(filePath, 1, 5)));

			writeData(filePath, "Data", 5);
			//now file content is "ABCDEData"
			
			appendData(filePath, "pankaj");
			//now file content is "ABCDEDatapankaj"
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void appendData(String filePath, String data) throws IOException {
		RandomAccessFile raFile = new RandomAccessFile(filePath, "rw");
		raFile.seek(raFile.length());
		System.out.println("current pointer = "+raFile.getFilePointer());
		raFile.write(data.getBytes());
		raFile.close();
		
	}

	private static void writeData(String filePath, String data, int seek) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "rw");
		file.seek(seek);
		file.write(data.getBytes());
		file.close();
	}

	private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws IOException {
		RandomAccessFile file = new RandomAccessFile(filePath, "r");
		file.seek(seek);
		byte[] bytes = new byte[chars];
		file.read(bytes);
		file.close();
		return bytes;
	}

}

That’s all for RandomAccessFile in java.

Java中的RandomAccessFile就是这样。

翻译自: https://www.journaldev.com/921/java-randomaccessfile-example

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值