Java 从文本文件中提取值

Java Extracting values from text files

我有很多文本文件(最多 20 个),每个文件都有这样的内容

21.0|11|1/1/1997
13.3|12|2/1/1997
14.6|9|3/1/1997

每个文件大约有 300 多行。

所以我面临的问题是,如何提取所有且仅提取第一个值 文件的内容。

例如我想提取值(21.0、13.3、14.6.....等),这样我就可以决定所有 20 个文件中的最大数量和最小数量。

我根据自己的理解编写了这段代码,以便在文件中体验它 但是没用

  String inputFileName = "Date.txt";
 File inputFile = new File(inputFileName);
 Scanner input = new Scanner(inputFile);
 int count = 0;
 while (input.hasNext()){
     double line = input.nextDouble(); //Error occurs "Exception in thread "main" java.util.InputMismatchException" 
     count++;
     double [] lineArray= new double [365];
     lineArray[count]= line;
     System.out.println(count);
      for (double s : lineArray){
       System.out.println(s);
          System.out.println(count);

还有这个

 String inputFileName = "Date.txt";
 File inputFile = new File(inputFileName);
 Scanner input = new Scanner(inputFile);

 while (input.hasNext()){
     String line = input.nextLine();
     String [] lineArray = line.split("//|");
      for (String s : lineArray){
       System.out.println(s+" ");
 }

我希望我说清楚了,谢谢

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
      String res = s.split("\|")[0];
    }
}

对于每一行文本,检查它是否包含竖线字符。如果是,则抓取文本的第一部分并将其解析为双倍。

double val = 0.0;
Scanner fScn = new Scanner(new File(“date.txt”));
while(fScn.hasNextLine()){   //Can also use a BufferedReader
    data = fScn.nextLine();
    if(data.contains("|"))    //Ensure line contains "|"
        val = Double.parseDouble(data.substring(0, data.indexOf("|")));  //grab value
}

或者你可以尝试一些流,很酷的东西

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MinMaxPrinter {

    public static void main(String[] args) {
        final List<String> files = Arrays.asList("file", "names", "that", "you", "need");

        new MinMaxPrinter().printMinMax(files);
    }

    public void printMinMax(List<String> fileNames) {
        List<Double> numbers = fileNames.stream()
                .map(Paths::get)
                .flatMap(this::toLines)
                .map(line -> line.split("\|")[0])
                .map(Double::parseDouble)
                .collect(Collectors.toList());

        double max = numbers.stream().max(Double::compare).get();
        double min = numbers.stream().min(Double::compare).get();

        System.out.println("Min: " + min + " Max: " + max);
    }

    private Stream<String> toLines(Path path) {
        try {
            return Files.lines(path);
        } catch (IOException e) {
            return Stream.empty();
        }
    }
}