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


This is a Java program that reads words from a file and finds the longest word in it. Here's how it works:

  • The program defines a class called Longest_Word.
  • The main method of this class creates an instance of Longest_Word and calls its find_LongestWords method.
  • The find_LongestWords method defines a String variable called long_word and initializes it to an empty string.
  • The method creates a Scanner object that reads input from a file called file.txt.
  • The method reads words from the file, one at a time, using the Scanner's next method. Each word is stored in a String variable called cur.
  • The method checks if cur is longer than long_word. If it is, long_word is updated to cur.
  • After all words have been read, the method prints out the value of long_word and returns it.

Note that the program assumes that the file file.txt exists in the same directory as the program. If the file is located elsewhere, you need to specify the full path to it. Also, the program doesn't handle cases where there are ties for the longest word; it simply returns the first longest word it finds.

Source Code

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Longest_Word
{
	public static void main(String[] args) throws FileNotFoundException {
		new Longest_Word().find_LongestWords();
	}
 
	public String find_LongestWords() throws FileNotFoundException {
		String long_word = "";
		String cur;
		Scanner input = new Scanner(new File("file.txt"));
 
		while (input.hasNext())
		{
			cur = input.next();
			if (cur.length() > long_word.length())
			{
				long_word = cur;
			}
		}
		System.out.println(long_word);
		return long_word;
	}
}

Output

Programs