0

What is the best way to read words from file knowing the line index? I want to read each word in the file and check if contains only digits. If it doesn't I want to print the word index and line index.

I'm currently using this, but I wonder if there is a way to do it without 2 loops.

private static void validateNumber ( String fileName )
{

    try ( BufferedReader reader = new BufferedReader ( new FileReader ( fileName ) ) )
    {

        String line = null;
        int lineIndex = -1;

        while ( ( line = reader.readLine ( ) ) != null )
        {
            lineIndex++;

            String [ ] words = line.trim ( ).split ( "[\\s]+" );

            for ( int i = 0; i < words.length; i++ )
            {
                System.out.println("Word " + i " at line " + lineIndex); 
            }

        }

    } catch ( FileNotFoundException e )
    {
        e.printStackTrace ( );
    } catch ( IOException e )
    {
        e.printStackTrace ( );
    }

}

2 Answers2

1

If you don't want to use 2 loops you can read the whole text then split on the "\n" character: String[] lines = text.split("\n"); Now you have an array of every line and you can retrieve any line by indexing the array. For example, line 5 is lines[4]

Ziad Halabi
  • 964
  • 11
  • 31
  • I dont think this answers his question – codeMan Apr 16 '15 at 07:42
  • My question was not complete. I want to read each word in the file and check if contains only digits. If it doesn't I want to print the word index and line index. –  Apr 16 '15 at 07:43
0

What is the best way to read words from file knowing the line index?

From Java 8 you can use the Stream API:

long lineIndex = 3; // e.g.: fourth line

String line = Files.lines(Paths.get("myfile.txt"))
                    .skip(lineIndex)
                    .findFirst()
                    .get();

But since you need to check every single line and you want to print the line number, the while loop is your best option as Java 8 streams don't have an index (find out why here).

Community
  • 1
  • 1
Javide
  • 2,477
  • 5
  • 45
  • 61