title: Using the scanner class to read a file
body: <p>Im trying to read a text file called "test.txt" with the scanner class. In the txt file its just a sentence like: "This is a txt file". This sentence is what I'm trying to get written out. But all i get written out is the name of the txt file when I use the command: java UDPClient test.txt localhost.</p>
  
  <p>Can anybody see something wrong in the code so that i can get it right? I have two possible codes. </p>
  
  <pre><code>Import java.net.*;
  Import java.io.*;
  Import java.util.*;
  
  public class Test_scanner { 
  
       public String readFile(String fileName) throws IOException {
  
           File file = new File("test.txt");
           StringBuilder fileContents = new StringBuilder((int)file.length());
           Scanner s = new Scanner(file);
           String lineSeparator = System.getProperty("line.separator");
  
       try {
         while (s.hasNextLine()) {
             fileContents.append(s.nextLine() + lineSeparator);
         }
             return fileContents.toString(); 
         } finally {
             s.close();
              }
      }
  }
  </code></pre>
  
  <p>I also have this code:</p>
  
  <pre><code>import java.net.*;
  import java.io.*;
  import java.util.*;
  
  public class Test_scanner {
  
      public static void readFile(String fileName) {
          try {
             File file = new File(fileName);
             Scanner scanner = new Scanner(file);
              while (scanner.hasNextLine()) {
                      System.out.println(scanner.nextLine());
              }
                       scanner.close();
              } catch (FileNotFoundException e) {
                      e.printStackTrace();
              }
      }
  </code></pre>