【问题标题】:read data from text file and filter content从文本文件中读取数据并过滤内容
【发布时间】:2015-06-01 13:51:42
【问题描述】:

我有一个文本文件,其中包含一些证券市场数据我想读取文件的内容到现在我能够读取全部内容但我需要的是读取特定行而不是全部内容并且我想存储要存储在变量中的特定行数据如何实现?

从我有这个代码读取数据。

public void loadPartsDataCleanly() throws FileNotFoundException
    {
        Part compart=new Part();
        String line=" ";
        File partsfile=new  File("C:/Users/ATOMPHOTON/workspace/anup/parts.txt");//put your file location path
    Scanner partscan=new Scanner(partsfile);
    try {
        while (partscan.hasNextLine()){
            String mystr=partscan.nextLine();
            System.out.println(mystr);


        }
        partscan.close();
    }

    catch (Exception e) 
    {
        e.printStackTrace();
    // TODO: handle exception
    }


}

}

【问题讨论】:

  • 你怎么知道你想读哪些行?它们总是在第 5、第 7 和第 42 行还是有一些特殊的格式?你想从中提取什么数据?
  • ya 这些线是固定的,比如第一家公司的第 2 3 和第 4 行,以及其他公司的第 1 行第 2 行和第 3 行 ...
  • 您的程序会逐行读取它,因此您可能希望在 while loop 中添加一个条件来存储特定的行
  • 添加计数器可能有助于确定当前行号
  • 我是java新手,完全不知道

标签: java file-handling


【解决方案1】:

您可以从以下位置更改您的部分:

while (partscan.hasNextLine()){
  String mystr=partscan.nextLine();
  System.out.println(mystr);
}
partscan.close();

int lineNo = 0;
List<String> theOnesICareAbout = new LinkedList<String>();
while (partscan.hasNextLine()){
  String line=partscan.nextLine();
  if (isOneOfTheImportantLines(lineNo)) {
    theOnesICareAbout.add(line);
  }
}
partscan.close();

你需要一个函数来告诉你给定的行号是否是你关心的:

boolean isOneOfTheImportantLines(int lineNo) {
  //YOUR LOGIC HERE
}

您可以添加额外的优化,例如不读取所有文件,但在获得所有您关心的信息后停止等。首先让它工作。如果它不起作用,它不起作用的速度有多快并不重要:)

【讨论】:

    【解决方案2】:

    这是一种更简洁的 java8 处理方式(从 IO 和字符串查找的角度来看)

    public class App {
    
        public static void main(String args[]) {
    
            Path path = Paths.get("C:\\full\\Path\\to\\file.txt");
    
            List<String> stringList = getLinesThatContain(path, "IBM");
    
    
            System.out.println(stringList);
    
        }
    
    
    // Note: No null-checking mechanisms
        public static List<String> getLinesThatContain(Path path, String match) {
            List<String> filteredList = null;
    
            try(Stream<String> stream = Files.lines(path)){
                // Filtering logic here
                 filteredList = stream.filter(line -> line.contains(match))
                                      .collect(Collectors.toList());
    
            } catch (IOException ioe) {
                // exception handling here
            }
            return filteredList;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      相关资源
      最近更新 更多