有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中FileReader中以空格作为命令行参数传递目录时出现异常

try (BufferedReader b = new BufferedReader(new FileReader(args[0]))) {
        System.out.println("Reading from file :" + args[0]);
        String s = null;
        while ((s = b.readLine()) != null) {
            System.out.println(s);
        }
    } catch (ArrayIndexOutOfBoundsException a) {
        System.out.println("No file specified, quitting !");
    } catch (FileNotFoundException fe) {
        System.out.println("File not found :" + args[0]);
    } catch (IOException ie) {
        System.out.println("Error reading file : " + ie.getMessage());
    }

这里的args[0]是:G:\Lab Practice\file。txt

输出: 未找到文件:G:\Lab

这是因为路径中有一个空间。 我也尝试过用args[0]+args[1]替换args[0],但没有效果。 有人能帮我弄清楚吗


共 (3) 个答案

  1. # 1 楼答案

    简单地用引号把论点引起来:

    java Class "G:\Lab Practice\file.txt"
    

    在没有空格的情况下,它将每个变量视为args数组中的独立参数,因此G:\Labargs[0],而Practice\file.txtargs[1]

    docs开始:

    This is because the space character separates command-line arguments. To have Drink, Hot, and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

  2. # 2 楼答案

    我想你是这样称呼你的程序的:

    java -jar application.jar G:\Lab Practice\file.txt
    

    这仅仅意味着你有两个参数-G:\Lab(在args[0])和Practice\file.txt(在args[1])。现在两者都没有任何空间

    你需要在通话中加上一些引号:

    java -jar application.jar "G:\Lab Practice\file.txt"
    
  3. # 3 楼答案

    你试过用引号吗

    比如:args[0] is : "G:\Lab Practice\file.txt"