简体   繁体   中英

Java Scanner Read from File

Let me first establish the following fact: I am new to java, so please be patient.

In my programming class, we were given an exercise to do at home using the Scanner class. The activity shows the following coding to exercise with:

import java.io.*;
import java.util.*;

public class FileReadWrite {

     public static void main(String[] args) throws FileNotFoundException {
          String[] strArr = new String[100];

          int size = 0;

          try {
               Scanner scFile = new Scanner(new File("Names1.txt"));
               while (scFile.hasNext()) {
                    strArr[size] = scFile.next();
                    size++;
               }
               scFile.close();

               for (int i = 0; i < size; i++) {
                    System.out.print(strArr[i] + " ");
               }
          } catch (FileNotFoundException e) {
               System.err.println("FileNotFoundException: " + e.getMessage());
          }

     }
}

The program seems to not be working correct. I use NetBeans to run the code, and when I run the code, it does not display the data in the text file, Names.txt. Why is that? The program does however Build completely without errors.

I have tried going through the Scanner class javadocs, but it's not helping me.

Please explain to me so that I can learn from the mistake made.

Thanks, Johan

I tried your code on my mac, and it works. So I thought you might input a wrong path of Names1.txt file.

In Java, when you simply use "what_ever_file_name.txt" as the path of file, Java will only search the file in your source code folder. If nothing found, a "FILE_NOT_FOUND_EXCEPTION" will be thrown.

I agree with user2170674. I also tried your code in a Windows machine, using Eclipse, and everything went well. Maybe you are putting your file in the wrong path. Two options:

  • you could use the full path, like (if you're using Windows) "C:\\Names1.txt";
  • or, a more generic solution, using JFileChooser:

      // create your FileChooser final JFileChooser chooser = new JFileChooser(); // open the FileChooser int returnValue = chooser.showOpenDialog(null); // if you select a file if (returnValue == JFileChooser.APPROVE_OPTION) { // get the file and do what you need File file = chooser.getSelectedFile(); } else { // throw an exception or just a message in the log... } 

Your code looks good.
Debug with a few messages.
At end, add a System.out.println() or System.out.flush() .
Move exception block location to just after file use (minimise try block size) and move close() within finally block.
Make sure you view Netbeans output window (Window -> Output -> Output)

public class FileReadWrite {

 public static void main(String[] args) throws FileNotFoundException {
      System.out.println("##### Starting main method...");
      String[] strArr = new String[100];

      int size = 0;

      try {
           Scanner scFile = new Scanner(new File("Names1.txt"));
           while (scFile.hasNext()) {
                strArr[size] = scFile.next();
                size++;
           }
           System.out.println("##### Finished scan.  Found %d tokens.", size);
      } catch (FileNotFoundException e) {
           System.err.println("FileNotFoundException: " + e.getMessage());
      } catch (Exception e) {
           System.err.println("Exception: " + e.getMessage());
           e.printStackTrace();
      } finally {
           if (scFile != null) {
               scFile.close();
               System.out.println("##### Closed scanner.");
           }
      }
      System.out.println("##### Printing tokens...");

      for (int i = 0; i < size; i++) {
           System.out.print(strArr[i] + " ");
      }
      System.out.println("");
      System.out.println("##### Exiting main.");
 }
}

Here's a working example. Perhaps try using a BufferedReader.

import java.io.*;
import java.util.Scanner;

public class ScanXan {
public static void main(String[] args) throws IOException {

    Scanner s = null;

    try {
        s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

        while (s.hasNext()) {
            System.out.println(s.next());
        }
    } finally {
        if (s != null) {
            s.close();
        }
    }
}
}

From http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM