w3resource

Java: Find the longest word in a text file


18. Find Longest Word in File

Write a Java program to find the longest word in a text file.

Sample Solution:

Java Code:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Exercise18 {
     public static void main(String [ ] args) throws FileNotFoundException {
              new Exercise18().findLongestWords();
         }

     public String findLongestWords() throws FileNotFoundException {

       String longest_word = "";
       String current;
       Scanner sc = new Scanner(new File("/home/students/test.txt"));


       while (sc.hasNext()) {
          current = sc.next();
           if (current.length() > longest_word.length()) {
             longest_word = current;
           }

       }
         System.out.println("\n"+longest_word+"\n");
            return longest_word;
            }
}

Sample Output:

general-purpose,

Flowchart:

Flowchart: Find the longest word in a text file


For more Practice: Solve these Related Problems:

  • Write a Java program to find and print the longest word in a text file, ignoring punctuation.
  • Write a Java program to determine the longest word in a file and display its length.
  • Write a Java program to scan a text file for the longest word and list all words that have the maximum length.
  • Write a Java program to identify the longest word in a file using Java streams and lambda expressions.

Go to:


PREV : Read First 3 Lines of File.
NEXT : Java Date, Time and Calender Exercises Home

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.