从文本文件中读取数据并过滤内容

时间:2015-06-01 13:51:43

标签: java file-handling

我有一个文本文件,其中有一些证券市场数据我想阅读文件的内容到目前为止我能够阅读整个内容但我需要的是阅读特定的行而不是整个内容,我想存储那个特定的行数据存储在变量中我该如何实现呢?

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

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
    }


}

}

2 个答案:

答案 0 :(得分: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
}

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

答案 1 :(得分:1)

这是一种更清洁的java8处理方式(从IO和String查找的角度来看)

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

}