【问题标题】:How to Access string in file by position in Java如何在Java中按位置访问文件中的字符串
【发布时间】:2013-01-04 11:30:23
【问题描述】:

我有一个包含以下内容的文本文件:

one
two
three
four

我想通过它在Java文本文件中的位置来访问字符串“三”。我在google上找到了子字符串概念但无法使用它。

到目前为止,我能够读取文件内容:

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

}

我想将子字符串概念应用于文件。它会询问位置并显示字符串。

 String Str = new String("Welcome to Tutorialspoint.com");
 System.out.println(Str.substring(10, 15) );

【问题讨论】:

  • 请不要用 Reader 包装 DataInputStream。您不需要 DataInputStream 所以删除它。 vanillajava.blogspot.co.uk/2012/08/…
  • 我想给程序 2 个子字符串位置,它会从文本文件中返回字符串。
  • 您要输出特定的行吗?或者该位置可能不是行号?
  • 不,我不想输出特定的行。例如 public class Test { public static void main(String[] args) { String str = "University"; System.out.println(str.substring(4,7)); } } 输出是“ers” 我的程序应该占据 2 个位置,并在具有该位置的文件中显示字符串。如果我放 (str.substring(4,7));根据文本文件,结果应该是“wo th”。
  • 编辑您的问题以添加有关您期望什么以及您的确切问题是什么的清晰信息。尽可能窄

标签: java file


【解决方案1】:

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

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 个字符,你必须从文件顶部开始读取并丢弃前 n-1 个字符。

【讨论】:

  • 或者只使用'InputStream.skip(numberOfBytes)'
  • @JayC667 并仔细检查返回值以确保它确实跳过了您要求它跳过的字节数 - 允许跳过少于 numberOfBytes
【解决方案2】:

在您的文本文件中查找\r\n(换行符)。这样你应该能够计算包含你的字符串的行数。

你的文件实际上是这样的

one\r\n
two\r\n
three\r\n
four\r\n

【讨论】:

  • 以这种方式可以做到。但我想通过它的开始和结束位置的 2 个位置访问文件中的刺“三”。我不是直接搜索字符串。
  • 所以你的位置是 row 和 lineStartIndex 和 lineEndIndex?
  • 更好:start = row + lineStartIndex 和 end = row + lineEndIndex。注意不要变成负数!
  • 换行符在不同平台上以不同方式编码。 \r\n 特定于 Windows 和 x86 BIOS 模式字符串,\n 用于类 Unix 操作系统,\r 用于 Mac(不确定后者是否仍然适用于基于 BSD 的 OS X)。因此,您不应依赖包含 \r\n 的文件来换行。
  • 完全正确,但在我看来,首先需要了解更多基本的事情(至少现在是这样)。
【解决方案3】:

您似乎在寻找this。我在那里发布的代码在字节级别上工作,所以它可能不适合你。另一种选择是使用 BufferedReader 并在这样的循环中读取单个字符:

String getString(String fileName, int start, int end) throws IOException {
    int len = end - start;
    if (len <= 0) {
        throw new IllegalArgumentException("Length of string to output is zero or negative.");
    }

    char[] buffer = new char[len];
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    for (int i = 0; i < start; i++) {
        reader.read(); // Ignore the result
    }

    reader.read(buffer, 0, len);
    return new String(buffer);
}

【讨论】:

    猜你喜欢
    • 2014-12-25
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多