【问题标题】:How to read file from command line in java?如何从java中的命令行读取文件?
【发布时间】:2016-02-20 05:03:41
【问题描述】:

我想进入命令行并输入输入,以便 BufferReader 可以访问该文件。我该怎么做?

输入将是“java TagMatching path_to_html_file.html”

// Importing only the classes we need
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TagMatching {

    public static void main(String[] args) {

        BufferedReader br = null;    
        // try to read the file
        try {

            br = new BufferedReader(new FileReader(**/*DONT KNOW WHAT TO DO*/**));
            String line;                        

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

【问题讨论】:

  • new FileReader(args[0])?
  • 我不知道该怎么做。
  • 详细说明你想做什么,我的意思是无法理解你真正在寻找什么
  • 您想读取文件中的所有行并将它们添加到字符串中吗?这个文件是不是很大,需要缓冲?

标签: java input bufferedreader


【解决方案1】:

要从控制台获取输入,您必须像这样使用 Scanner;

Scanner in = new Scanner(System.in); 
System.out.println("Enter file path");
String s = in.nextLine(); //C:\\testing.txt

并在 FIleReader 中使用该文件路径,如下所示;

br = new BufferedReader(new FileReader(s));

【讨论】:

    【解决方案2】:

    输入将是java TagMatching path_to_html_file.html

    在应用名称 (TagMatching) 之后,您会找到参数 (path_to_html_file.html),这是 main 方法的 String[] args,因此只需使用它们,在本例中为 args[0]

    public static void main(String[] args) {
        BufferedReader br = null;    
        // try to read the file
        try {
            // check if there are some arguments 
            if (null != args[0] && 
                // lenght > 5 because a.html will be shortest filename
                args[0].lenght > 5 && 
                // check if arguments have the correct file extension
                args[0].endsWith(".html")) 
            {
                br = new BufferedReader(new FileReader(args[0]));
                // do more stuff
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

    • @Shivam 在发布之前阅读我的答案的第一行怎么样? a.txt 必须被忽略
    【解决方案3】:

    完全适用于 args[0]。

    所以,br = new BufferedReader(new FileReader(args[0])); 将按照提问者的意图行事

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      相关资源
      最近更新 更多