Error capturing value of a text file in java

0

Good I have an error when printing the results of a text file I separated them with a split and I create a String[] columns and with a String dato1 = String.valueOf(columns[0]); I assigned the value but when printing this String no it brings me as a result all the data in that file, only some of them will give you an example of how my text file is composed.

Figure 1:

fecha1   hora de e/s      13:36:57 13:43:22           6,24T  
fecha2   hora de e/s      13:43:40 13:53:22          10,77T  
fecha3   hora de e/s      13:53:47 14:03:56          11,56T  
fecha4   hora de e/s      14:04:40 14:13:47          11,13T  
fecha5   hora de e/s      14:14:16 14:22:36          12,33T   

At the time of printing, it only prints the value of 10,77 down to 6,24 does not take it but if the file is placed in this way

Figure 2:

6,24T  
10,77T  
11,56T  
11,13T  
12,33T 

If I print them well but the text file is automatically generated as shown in figura 1 this is the code used.

  while ((linea = br.readLine()) != null) {
            columns = linea.split("  ");
            datos date = new datos();
            String dato1 = String.valueOf(columns[0]);
              System.out.println(dato1);
}
    
asked by Alexander Villalobos 26.06.2017 в 15:16
source

2 answers

3

To solve this you have two options:

One is that when you get to look for the number, check if it really is in that position (that is, that that position of the vector is not empty).

If not, I would recommend a reading of the positional line, since all the rows start in the same place with a lot of spaces.

Then you can do linea.substring(0,7) to get fecha1 , and from then on, do linea.substring(8,15).trim() to get hora de e/s , etcetera, then you avoid the problem if the spaces that come forward are many or few.

    
answered by 26.06.2017 / 16:24
source
1

What you must do is convert the line that has 2 spaces or more into something else (eg -----) and then do the split.

    while((linea=br.readLine())!=null){
        //si hay 2 espacios o mas los convierte a -----
        String auxLinea = linea.replaceAll("(  +)","-----").trim();
        columns = auxLinea.split("-----");          
        String dato1 = String.valueOf(columns[3]);
          System.out.println(dato1);
    }

Another option would be to use a regular expression and take a number separated by "," and ending in "T".

String regex = "([0-9]+(\,[0-9][0-9]?)?T)";
Pattern p = Pattern.compile(regex);

while((linea=br.readLine())!=null){
    Matcher m = p.matcher(linea);
    m.find();
    System.out.println(m.group(1));         
}
    
answered by 26.06.2017 в 16:28