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



运行程序时,如何让用户决定文件名??我的文件名被分配给一个名为"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();
    }

首先,像一样更改您的使用消息

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

然后,

File f=new File((args.length < 1) ? "ef.txt" : args[0]);
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();
}

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

您可以通过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();
    }
}

相关内容

  • 没有找到相关文章

最新更新