Java Extracting values from text files

11,117

Solution 1

For each line of text, check whether it contains the pipe character. If it does, grab the first portion of the text and parse it to double.

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
}

Solution 2

Or you could try some streams, cool stuff

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();
        }
    }
}
Share:
11,117
John
Author by

John

Updated on June 04, 2022

Comments

  • John
    John almost 2 years

    I have many text files (up to 20) and each file has it's contents like this

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

    and every file has approximately more than 300 lines.

    so the problem I'm facing is this, how can I extract all and only the first values of the file's content.

    for example I want to extract the values (21.0,13.3,14.6.....etc) so I can decide the max number and minimum in all of the 20 files.

    I have wrote this code from my understanding to experience it on of the files but it didn't work

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

    and this one too

     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+" ");
     }
    
    • Note: I'm still kind of a beginner in Java

    I hope I was clear and thanks

    • isaias-b
      isaias-b over 8 years
      This question deals about doing your work. This site is supposed to be used to manage specific programming problems. Provide your attempts and if you have a certain problem post a specific question.
    • user3437460
      user3437460 over 8 years
      @John Do you know how to read a line of text from the textfile?
    • John
      John over 8 years
      Yes I do know how to read from the textfile
    • John
      John over 8 years
      you can see my work in the question it was what I tried so far but no luck
    • Tom
      Tom over 8 years
      " but it didn't work " Any chance to get more information about your problem, than this? :)
    • RealSkeptic
      RealSkeptic over 8 years
      Your second attempt is nearly right. You have to note the difference between a slash / and a backslash \​.
    • John
      John over 8 years
      @Tom well in first code I got the Error Exception in thread "main" java.util.InputMismatchException
    • John
      John over 8 years
      @RealSkeptic yes right it was a mistake there and I noticed it thanks but still it doesn't solve my problem yet , how do I extract the value now ?
    • Tom
      Tom over 8 years
      Well, do you like to post that info in your question? How should we know, that you have this problem if you don't tell us about it? Btw: please don't forget the exception stacktrace. And please mark the line where the exception occurs.
  • Phani
    Phani over 8 years
    Can you please explain the code required on how it would resolve the issue?
  • John
    John over 8 years
    Thanks I really needed to know how to grab the value thanks again
  • John
    John over 8 years
    Thanks I really appreciate your effort