对于一个100兆大小的文本文件,如果想要查询某字符串所在位置,可以采用以下两种方法:
- 逐行读取文本文件,对每一行进行字符串匹配
这种方法适用于文本文件比较小的情况,可以使用Java的BufferedReader逐行读取文件,并对每一行进行字符串匹配。具体实现可以参考以下代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SearchStringInFile {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String searchString = "targetString";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
if (line.contains(searchString)) {
System.out.println("Found target string at line " + lineNumber);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 使用内存映射文件进行字符串匹配
如果文本文件比较大,逐行读取文件会比较耗时。可以使用Java的内存映射文件(MappedByteBuffer)来加速字符串匹配。具体实现可以参考以下代码:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class SearchStringInFile {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String searchString = "targetString";
try (RandomAccessFile file = new RandomAccessFile(filePath, "r");
FileChannel channel = file.getChannel()) {
long fileSize = channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
byte[] bytes = new byte[searchString.length()];
for (int i = 0; i < fileSize; i++) {
buffer.get(bytes);
if (new String(bytes).equals(searchString)) {
System.out.println("Found target string at position " + i);
}
buffer.position(i + 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这种方法使用内存映射文件,可以将文件映射到内存中,然后直接在内存中进行字符串匹配,速度比逐行读取文件要快。但是需要注意的是,这种方法会占用较多的内存,如果内存不足,可能会导致OutOfMemoryError。
new RandomAccessFile(filePath, "r"); 这里的 "r"是什么意思
在Java中,RandomAccessFile是一个可以读写文件的类,它支持随机访问文件,即可以在文件的任何位置读写数据。在创建RandomAccessFile对象时,需要指定访问模式,包括"r"、"rw"、"rws"和"rwd"四种模式。
其中,"r"模式表示以只读方式打开文件,如果文件不存在,则会抛出FileNotFoundException异常。在只读模式下,RandomAccessFile对象只能读取文件内容,不能修改文件内容。
示例代码:
RandomAccessFile file = new RandomAccessFile("path/to/file.txt", "r");
"rw"模式表示以读写方式打开文件,如果文件不存在,则会创建一个新的文件。在读写模式下,RandomAccessFile对象可以读取和修改文件内容。
示例代码:
RandomAccessFile file = new RandomAccessFile("path/to/file.txt", "rw");
"rws"模式表示以读写方式打开文件,并且要求每次修改文件内容后,立即将修改的内容写入到磁盘中。在读写同步模式下,RandomAccessFile对象可以读取和修改文件内容,并且可以保证修改的内容立即写入到磁盘中。
示例代码:
RandomAccessFile file = new RandomAccessFile("path/to/file.txt", "rws");
"rwd"模式与"rws"模式类似,也是以读写方式打开文件,并且要求每次修改文件内容后,立即将修改的内容写入到磁盘中。不同的是,"rwd"模式只会将修改的内容写入到文件的数据区域,而不会将文件的元数据(如文件大小和修改时间)写入到磁盘中。
示例代码:
RandomAccessFile file = new RandomAccessFile("path/to/file.txt", "rwd");
在使用RandomAccessFile时,需要根据具体的需求选择不同的访问模式。