2017-02-08 17 views
-1

charを含むテキストファイルから、java.io.File,Scanner、ファイルが見つかりませんという例外のみを使用して2次元配列にデータを読み込むにはどうすればよいですか?ファイルを2次元文字配列として読み取る

ここでは、ファイル内で2D配列に読み込む方法を示します。

public AsciiArt(String filename, int nrRow, int nrCol){ 
    this.nrRow = nrRow; 
    this.nrCol = nrCol; 

    image = new char [nrRow][nrCol]; 

    try{ 
     input = new Scanner(filename); 

     while(input.hasNext()){ 

     } 
    } 
} 

答えて

1

FileNotFoundExceptionクラスを含めるには、java.io.*(または必要な場合は必要な特定のクラス)をインポートしていることを確認してください。ファイルを正確に解析する方法を指定していないため、2D配列をどのように埋めるかを示すのは少し難解でした。ただし、この実装ではScanner、File、およびFileNotFoundExceptionが使用されます。

public AsciiArt(String filename, int nrRow, int nrCol){ 
    this.nrRow = nrRow; 
    this.nrCol = nrCol; 
    image = new char[nrRow][nrCol]; 

    try{ 
     Scanner input = new Scanner(new File(filename)); 

     int row = 0; 
     int column = 0; 

     while(input.hasNext()){ 
      String c = input.next(); 
      image[row][column] = c.charAt(0); 

      column++; 

      // handle when to go to next row 
     } 

     input.close(); 
    } catch (FileNotFoundException e) { 
     System.out.println("File not found"); 
     // handle it 
    } 
} 
+0

あなたのおかげで、私の記憶を揺さぶってくれてありがとう。私は別のコードを流してきました、そして時々私は忘れました。 –

0

それを行うのラフな方法は、次のようになります。

File inputFile = new File("path.to.file"); 
    char[][] image = new char[200][20]; 
    InputStream in = new FileInputStream(inputFile); 
    int read = -1; 
    int x = 0, y = 0; 
    while ((read = in.read()) != -1 && x < image.length) { 
     image[x][y] = (char) read; 
     y++; 
     if (y == image[x].length) { 
      y = 0; 
      x++; 
     } 
    } 
    in.close(); 

は、しかし、はるかに優れた、より効率的であることが、あなたが原則になるだろう、他の方法があることを確認イム。

関連する問題