簡體   English   中英

嘗試從Java的Linux命令行讀取文件時發生ArrayIndexOutOfBoundsException:0?

[英]ArrayIndexOutOfBoundsException:0 occurs when trying to read in a file from the Linux command line in Java?

因此,我試圖將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();
  }
}

更新:

您的教授正在要求您使用類似以下的命令使用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");
}

根據您的描述和您提供的鏈接(應該在問題中,而不是評論),您的教授希望您編寫一個程序,以POSIX的身份通過“ standard in”(STDIN)接受文件的內容樣式外殼命令行使用重定向。

如果確實需要這樣做,則不能只讀取作為參數給出的文件,而是需要更改程序以使其從STDIN中讀取。 這里的關鍵概念是“ <”不適用於程序參數列表。 運行Java進程的外殼(Bash,Ksh等)將使用它,並且在右側的文件和左側的進程之間使用“管道”設置。 在這種情況下,該進程就是運行程序的Java進程。

嘗試搜索“ java STDIN”以獲取有關如何編寫可讀取其標准的Java程序的一些想法。

順便說一下,如果以這種方式使用重定向運行程序時,由於ArrayIndexOutOfBoundError導致程序崩潰,則程序中仍然存在錯誤。 在外殼程序完成命令行處理后,您需要測試並處理文件參數為0的情況。 如果要獲得滿分,則需要處理錯誤和邊緣情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM