1   import java.io.BufferedReader;
2   import java.io.FileReader;
3   import java.io.IOException;
4   
5   /**
6    * TIE120 Programming 2, Exam 17.3.2004, Question 3, Example solution.
7    * 
8    * @author Heikki Kainulainen
9    * @version 1.0, 31.03.2004
10   */
11  public class LongestWord {
12  
13      /**
14       * Return the longest word of the text file.
15       * 
16       * @param fileName
17       *            the name of the file to read from.
18       * @return the longest word.
19       * @throws IOException
20       *             if an I/O error occurs.
21       */
22      public static String getLongestWord(String fileName) throws IOException {
23          String longest = "";
24          BufferedReader in = null;
25          try {
26              in = new BufferedReader(new FileReader(fileName));
27              String line;
28              while ((line = in.readLine()) != null) {
29                  String[] parts = line.split(" ");
30                  for (int i = 0; i < parts.length; i++) {
31                      String s = parts[i];
32                      if (s.length() > longest.length()) {
33                          longest = s;
34                      }
35                  }
36              }
37          } finally {
38              if (in != null) {
39                  in.close();
40              }
41          }
42          return longest;
43      }
44  
45      public static void main(String[] args) {
46          try {
47              System.out.println(getLongestWord("C:\\kissa.txt"));
48          } catch (IOException e) {
49              e.printStackTrace();
50          }
51      }
52  }
53