java如何定位字符串的位置,如何在Java中按位置访问文件中的字符串

博客围绕在Java中定位文本文件里字符串位置展开。博主已能读取文件内容,但运用substring概念定位字符串遇问题。给出解决方案,若知文件字节偏移量可直接定位,若文件是可变宽度编码,需从头读取并丢弃前n - 1个字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a text file with the following contents:

one

two

three

four

I want to access the string "three" by its position in the text file in Java.I found the substring concept on google but unable to use it.

so far I am able to read the file contents:

import java.io.*;

class FileRead

{

public static void main(String args[])

{

try{

// Open the file that is the first

// command line parameter

FileInputStream fstream = new FileInputStream("textfile.txt");

// Get the object of DataInputStream

DataInputStream in = new DataInputStream(fstream);

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;

//Read File Line By Line

while ((strLine = br.readLine()) != null) {

// Print the content on the console

System.out.println (strLine);

}

//Close the input stream

in.close();

}catch (Exception e){//Catch exception if any

System.err.println("Error: " + e.getMessage());

}

}

}

I want to apply the substring concept to the file.It asks for the position and displays the string.

String Str = new String("Welcome to Tutorialspoint.com");

System.out.println(Str.substring(10, 15) );

解决方案

If you know the byte offsets within the file that you are interested in then it's straightforward:

RandomAccessFile raFile = new RandomAccessFile("textfile.txt", "r");

raFile.seek(startOffset);

byte[] bytes = new byte[length];

raFile.readFully(bytes);

raFile.close();

String str = new String(bytes, "Windows-1252"); // or whatever encoding

But for this to work you have to use byte offsets, not character offsets - if the file is encoded in a variable-width encoding such as UTF-8 then there's no way to seek directly to the nth character, you have to start at the top of the file and read and discard the first n-1 characters.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值