ArrayIndexOutOfBoundsException:尝试从Java中的Linux命令行读取文件时出现0?

时间:2016-04-06 00:33:57

标签: java linux

所以我试图从Linux命令行接受一个文本文件到我的Java程序中,但是编译器给了我标题中提到的错误。它表示错误发生在" String fileName = args [0];"的行上。有谁碰巧知道为什么? 这是我的代码:

public class Parsons_Decoder
{
  // method: main
  // purpose: receives key-phrase and sequence of integers and
  // prints the secret message to the screen.
  public static void main(String[] args) throws IOException
  {
    String fileName = args[0];

    // reads incoming file (if it exists) and saves the key-phrase to
    // String variable "keyPhrase"
    File testFile = new File(fileName);

    if(!testFile.exists())
    {
      System.out.println("\nThis file does not exist.\n");
      System.exit(0);
    }

    Scanner inputFile = new Scanner(args[0]);
    String keyPhrase = inputFile.nextLine();

    // creates an ArrayList and stores the sequence of integers into it
    ArrayList<Integer> numArray = new ArrayList<Integer>();

    while(inputFile.hasNextInt())
    {
      numArray.add(inputFile.nextInt());
    }

    // decodes and prints the secret message to the screen
    System.out.println();
    System.out.print("Your secret message is: ");

    for(int i = 0; i < numArray.size(); i++)
    { 
      int num = numArray.get(i);
      System.out.print(keyPhrase.charAt(num));
    }
    System.out.println("\n");

    //keyboard.close();
    inputFile.close();
  }
}

2 个答案:

答案 0 :(得分:4)

<强>更新

你的教授要求你用stdin读取一个文件,使用如下命令:

java Diaz_Decoder < secretText1.txt

您的main()方法应如下所示:

public static void main(String[] args) throws IOException {
    // create a scanner using stdin
    Scanner sc = new Scanner(System.in);

    String keyPhrase = inputFile.nextLine();

    // creates an ArrayList and stores the sequence of integers into it
    ArrayList<Integer> numArray = new ArrayList<Integer>();

    while (inputFile.hasNextInt()) {
        numArray.add(inputFile.nextInt());
    }

    // decodes and prints the secret message to the screen
    System.out.println();
    System.out.print("Your secret message is: ");

    for (int i = 0; i < numArray.size(); i++) {
        int num = numArray.get(i);
        System.out.print(keyPhrase.charAt(num));
    }

    System.out.println("\n");
}

答案 1 :(得分:1)

根据您的描述和您提供的链接(应该在问题中,而不是评论),您的教授希望您编写一个程序,通过&#34;标准在&#34;中接受文件内容。 (STDIN)使用重定向作为POSIX样式的shell命令行运行时。

如果这确实是一个要求,你不能只读取作为参数给出的文件,但需要更改程序,使其从STDIN读取。这里的关键概念是&#34;&lt;&#34;不适用于您的程序参数列表。它将由运行Java进程的shell(Bash,Ksh等)和&#34; pipe&#34;在右侧的文件和左侧的过程之间进行设置。在这种情况下,该过程是运行程序的Java进程。

尝试搜索&#34; java STDIN&#34;获得一些关于如何编写可以读取其标准的Java程序的想法。

顺便说一句,如果你的程序在以这种方式运行重定向时遇到ArrayIndexOutOfBoundError崩溃,它仍然有一个错误。在shell完成处理命令行之后,您需要测试并处理有0个文件参数的情况。如果需要满分,则需要处理错误和边缘情况。