简体   繁体   English

如何使用扫描仪从命令行读取文件

[英]How can I read a file from the command line using scanner

It wont prompt the user to enter file? 它不会提示用户输入文件吗? Please help me 请帮我

public static void main (String args []){
if (0 < args.length) { 
     File inFile = new File(args[0]); // Make sure the file exists, can read, etc...
     while (!inFile.exists()) {
      Scanner console = new Scanner (inFile);
      System.out.println ("Input file:"); //prompt user to input file
         String inFileName = console.nextLine();
         System.out.println ("Input file:"); //prompt user to input file
         inFileName =inFileName.trim(); //get rid of whitespace
           System.out.println(inFileName);
         inFile = new File (inFileName);
      } 

The old way : 旧方法:

BufferedReader reader = new BufferedReader( new InputStreamReader( System.in)); String userInput = reader.readLine();

The new way : 新方法:

Console console = System.console(); 
if( console != null) { String userInput = console.readLine();

对于扫描仪,您需要使用。

Scanner console = new Scanner(System.in);

I suppose you can do the expected task with few lines of code. 我想您可以用几行代码来完成预期的任务。

public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        System.out.println("Input file : ");
        String inFile = userInput.next();
        System.out.println("Input file is " + inFile);
    }

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

相关问题 如何使用Java中的命令行将文本文件读入扫描仪 - How to read a text file in to a scanner using command line in Java 如何让我的扫描仪读取文件中的下一行? - How can I get my scanner to read the next line in the file? 如何使用扫描仪从文件中读取一行中的某个字符串? - How do I read a certain string on a line from a file, using scanner? 我可以使用扫描仪从文件中读取字节数组吗? - Can I read a byte array from file using scanner? Java使用扫描程序读取文件然后读取行 - Java Using Scanner to Read File and Then Read Line 如何使用扫描仪在文本文件中切换一行的 position 和其后的行? - How can I switch the position of a line with the line after it in a text file using a Scanner? 如何修改此Java程序以从命令行中指定的文件中读取名称? - How can I modify this Java program to read in the names from a file designated in the command line? 如何使用扫描仪从同一行读取多个浮点数? - How do I read multiple floats from the same line with a scanner? 如何从命令行读入文本文件 - How do I read in a text file from the command line 在Java中,使用扫描仪从.txt文件中读取数据,以便我可以使用该数据作为构造函数参数来生成对象 - In Java, using a Scanner to read in data from a .txt file so I can generate objects with that data as constructor parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM