如何在执行时设置文件变量名称

时间:2014-10-15 17:15:10

标签: java io linked-list

运行程序时,如何让用户决定文件名?我的文件名被分配给一个名为" f"的变量。并且目前是硬编码的,但我如何运行程序并同时指向某个文件....例如

如何将此分配给" f" ??

System.out.println("用法:java CheckBalanced");

   ListReferenceBased stack = new ListReferenceBased();
    int exception=0;
     File f=new File("ef.txt");


     FileReader fr = null;
    try {
        fr = new FileReader(f);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

3 个答案:

答案 0 :(得分:1)

首先,更改您的使用信息,如

System.out.println("usage: java CheckBalanced <FILE>");

然后,

File f=new File((args.length < 1) ? "ef.txt" : args[0]);

答案 1 :(得分:1)

I suggest you to use  Scanner class which is present in java.util package so you import this package in our program.

Scanner a = new Scanner(System.in);

Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below :-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string

in your case you can use string (nextLine)

你的代码看起来应该是这样的

ListReferenceBased stack = new ListReferenceBased();
int exception=0;
 // add the following code
  String fileName;
  Scanner in = new Scanner(System.in);
  System.out.println("Enter the file name in .txt");
  fileName = in.nextLine();


 File f=new File(fileName);     

 FileReader fr = null;
try {
    fr = new FileReader(f);
} catch (FileNotFoundException e) {

    e.printStackTrace();
}

答案 2 :(得分:0)

如果这有一个主方法,请执行以下操作:

您可以通过java CheckBalanced PathToFileName调用该程序,其中PathToFileName是文件系统上文件的位置。

一个例子是java CheckBalanced "C:/ef.txt"

public static void main(String[] args) {

    String pathToFile = args[0];

    ListReferenceBased stack = new ListReferenceBased();
    int exception = 0;
    File f = new File(pathToFile);

    FileReader fr = null;
    try {
        fr = new FileReader(f);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

}