简体   繁体   English

readfile来自文本文件元素java

[英]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? 我正在尝试读取.txt文件,但是当我使用调试器时它会被困在下一行? 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 System.in标准输入 (或“终端”),用于询问用户文件名
  • the file with the name you get from the user 具有您从用户获得的名称的文件

When you call name = kb.nextLine(); 当你调用name = kb.nextLine(); , you're asking the parameter (the Scanner built with System.in ) for its next line. ,您要求参数(使用System.in构建的扫描仪)作为下一行。 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. 如果在IDE中运行,请切换到“控制台”选项卡并在其中输入。

As quazzieclodo noted above, you probably only need to call readLine once. 正如上面提到的quazzieclodo,您可能只需要调用readLine一次。

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. 之后,您可以根据readFileInfo返回的文件打开第二个扫描程序,然后您实际上正在按预期读取文本文件。

Assuming that your intention is to use Scanner to read a text file: 假设您的意图是使用Scanner读取文本文件:

 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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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