如何在Java中按位置访问文件中的字符串 [英] How to Access string in file by position in Java

查看:173
本文介绍了如何在Java中按位置访问文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其内容如下:

I have a text file with the following contents:

one
two
three
four

我想通过Java文本文件中的位置访问字符串三".我在Google上找到了子字符串概念,但无法使用它.

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) );

推荐答案

如果您知道感兴趣的文件中的 byte 偏移量,那么它很简单:

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

但是要执行此操作,您必须使用字节偏移量,而不是字符偏移量-如果文件以可变宽度编码(例如UTF-8)进行编码,则无法直接查找第n个 character ,则必须从文件顶部开始,读取并丢弃前n-1个字符.

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.

这篇关于如何在Java中按位置访问文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆