如何读取字符串数据在文本文件中的特定位置 [英] How to read a specific position of a string data in a text file

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

问题描述

我正在处理一个包含多达一千行的文本文件。在一个文本文件中有多个页眉和页脚。所以我不需要处理包含@h和@f的行。它告诉我一个事务的开始和结束(数据库事务,我将在一个事务中将这些记录保存到DB)。

I am processing a text file which contains up to a thousand lines. There are multiple headers and footers in one text file. So I don't need to process the line which contains @h and @f. It tells me the beginning and end of a transaction (Database transaction, I will save those records to DB in one transaction).

示例记录如下。虽然行达到一千行,列最多为40列。从每行我只是寻找一个特定的数据,(例如,我需要一个名字从位置8到30,年从位置60到67等等)。这个位置可能是下一个空格或字符串之间。所以我不想把每行的数据放入缓冲区/内存来处理它,因为我只对其中的很少感兴趣。 CSV文件是否允许从行中的特定位置获取数据?我应该使用什么来获得更好的性能(尽可能快地处理数据,而不占用很多内存。)? 我使用的是Java

A sample record is below. Though the line reaches up to a thousand lines and the columns are up to 40 columns. From each line I am only looking for a specific data i.e (e.g i need to get a name from postion 8 to 30, year from position 60 to 67 and the likes). This position might be next a space or between strings. So I don't want to put the data of each line in to buffer/memory to process it because, I am only interested on few of them. Does CSV file allows to get a data from a specific position in a line? What should I use to get a better performance (to process the data as quick as possible without taking much memory.)? I am using Java

@h Header
@074VH01MATT    TARA   A5119812073921 RONG HI  DE BET IA76200  201108222   0500  *
@074VH01KAYT    DJ     A5119812073921 RONG DED CR BET IA71200  201108222   0500  *
@f Footer

@h Header
@074VH01MATT    TARA   A5119812073921 RONG HI  DE BET IA76200  201108222   0500  *
@074VH01KAYT    DJ     A5119812073921 RONG DED CR BET IA71200  201108222   0500  *
@f Footer


推荐答案

这是我的解决方案:

import java.io.*;
class ReadAFileLineByLine 
{
 public static void main(String args[])
  {
  try{
    FileInputStream fstream = new FileInputStream("textfile.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;
    //Loop through and check if a header or footer line, if not
    //equate a substring to a temp variable and print it....
    while ((strLine = br.readLine()) != null)   {
      if (!(strLine.charAt(1) == "h" || strLine.charAt(1) == "f"))
        String tempName = strLine.substring(8,31);
      System.out.println(tempName);
    }
    //Close the input stream
    in.close();
  } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

寻找?

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

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