简体   繁体   中英

readfile in from text file elements java

I'm trying to read in a .txt file in but when i use debugger it gets stuck on nextline? Is there some logic error that im doing? It's all being stored into an array through multiple objects:

public static File readFileInfo(Scanner kb)throws FileNotFoundException


{
     System.out.println("Enter your file name");
      String name = "";
      kb.nextLine();
      name = kb.nextLine();
      File file = new File(name);
      return file;
   }

The scanner I passed into it is:

Scanner fin = null, kb = new Scanner(System.in);
  File inf = null;

  inf = FileUtil.readFileInfo(kb);
  fin = new Scanner(inf);

You're reading from two different "files" here:

  • System.in , the standard input (or "terminal"), which you're using to ask the user for a filename
  • the file with the name you get from the user

When you call name = kb.nextLine(); , you're asking the parameter (the Scanner built with System.in ) for its next line. Generally, that will actually block ("hang") until it receives another line of input (the filename) from the user. If running from a command line, enter your text into that window; if running in an IDE, switch to the Console tab and enter it there.

As quazzieclodo noted above, you probably only need to call readLine once.

After that, you can open up your second Scanner based on the File that readFileInfo returns, and then you're actually reading from a text file as expected.

Assuming that your intention is to use Scanner to read a text file:

 File file = new File("data.txt");

    try {
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            System.out.println(line);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

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