Why does hasNext () and hasNextLine () say the file is empty if there is content?

1

This is part of my list (it is contained in a .txt file):

  • Gladiator (The Gladiator) (2000) 8.5

    Rate

    The Dark Knight

  • The Dark Knight (2008) 9

    Rate

    Slumdog Millionaire

  • Slumdog Millionaire (2008) 8

    Rate

    Infiltrators

  • Infiltrados (2006) 8,5

    Rate

  • And this is my code:

    File input = new File ("movies.txt");
    Scanner in = new Scanner (input);
    
        Scanner reader = new Scanner (System.in); 
    PrintWriter out = new PrintWriter("MovieList.txt");
    
        System.out.println(in.hasNext()+" "+ in.hasNextLine());       
        while (in.hasNextLine()){
            String word = in.nextLine();
    
    
            System.out.println(word);
            if ( Character.isDigit(word.charAt(0)) )
                out.println(word);
    
        }
    
        in.close();
        out.close();
    
    
    }
    

    As you can see, the file includes a list of movies. However, when copying them from the internet, the format in which they were copied is a bit erroneous. My goal is to iterate through each line and if the first character of the line is a number, write it in a new list (generating the correct format). Unfortunately, System.out.println (in.hasNext () + "" + in.hasNextLine ()); they come out as false so the loop never activates.

        
    asked by nachomanchis 22.11.2018 в 02:23
    source

    2 answers

    0

    Here is an algorithm to read any flat text file. You can adapt it to your requirements

    @Override
    public Stream<String> leerAchivoLocal(String nombreArchivo) {
        Stream<String> lineas = null;
        Path ruta = null;
    
        try {
    
            lineas = Files.lines(Paths.get(ruta), Charset.forName("UTF-8"));
    
    
        } catch (IOException | URISyntaxException ex) {
            Logger.getLogger(ArchivoImpl.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
          // if(lineas != null) lineas.close();
        }
    
        return lineas;
    }
    
        
    answered by 22.11.2018 в 12:55
    -1

    The problem is that the file has blank lines, the first line reads, but the second has no content, in that case you should skip one line and validate the next. Now when you make System.out.println(in.hasNext()+" "+ in.hasNextLine()); you advance the iterator, it's as if you read a line but you will not use the content.

        
    answered by 22.11.2018 в 07:11