[英]How to read file from command line in java?
I want to go to command line and type the input, so the BufferReader can have access to the file. 我想转到命令行并输入输入,因此BufferReader可以访问该文件。 How am i supposed to do that ? 我应该怎么做?
The input will be "java TagMatching path_to_html_file.html" 输入将为“ 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();
}
}
}
The input will be
java TagMatching path_to_html_file.html
输入将是java TagMatching path_to_html_file.html
After the name of the app ( TagMatching
) you find the arguments ( path_to_html_file.html
) this are the String[] args
of the main method, so just use them, in this case args[0]
: 在应用程序名称( 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();
}
}
To get the input from the console you have to use Scanner like this; 要从控制台获取输入,您必须使用Scanner这样;
Scanner in = new Scanner(System.in);
System.out.println("Enter file path");
String s = in.nextLine(); //C:\\testing.txt
And to use that file path in the FIleReader use like this; 要在FIleReader中使用该文件路径,请使用如下代码;
br = new BufferedReader(new FileReader(s));
Exactly works with args[0]. 与args [0]完全一样。
So, br = new BufferedReader(new FileReader(args[0]));
因此, br = new BufferedReader(new FileReader(args[0]));
will act as the questioner intends 将按照提问者的意图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.