2016-05-19 4 views
0

Update: Я использую «\ п» к многообразной каждой строке в методе сохранений, который указан в API. Это означает, что readLine должен правильно найти каждую отдельную строку в файле, назначить ее значение и закрыть после того, как прочитал последнюю строку. Тем не менее, я все еще получаю "нуль" (NullPointerException) в качестве выходного сигнала ...значение txt.file Чтения (присвоение) в Java

Это как нуль указано в API:

(ReadLine) Возвращает:

Строка, содержащая содержимое строки, не включая любые линии прекращения символов, или ноль, если конец потока был достигнут


Я пытаюсь прочитать txt-файл и назначить его строки в массив int [] [].

Это пример того, как мой savegame.txt файл выглядит следующим образом:

0 

0 

-1 

0 

1 

-1 

1 

0 

0 

Каждая строка представляет собой Инт-значение. Мой метод saveGame записывает текущие значения массива «gameBoard» в указанный выше файл. Этот пример представляет собой следующее состояние игры:

| | O 

| X | O 

X | | 

Однако, когда я пытаюсь прочитать savegame.txt файл с моим методом loadGame, который присваивает каждому отдельную позицию игры [0] [0] - [2] [2], ее соответствующие значения, я получаю нуль как выход, и игра начинается с emp массив. Из моей логики мой метод loadGame должен читать каждую строку отдельно и анализировать его значение String в Integer, которое может быть интерпретировано моим массивом int [] [] arrayBoard. Интересно, почему это работает неправильно.

FileManagement.class

package storagePack; 

import structurePack.Board; 

import java.io.*; 
import java.util.Scanner; 

/** 
* The FileManagement-Class is responsible for the saving and loading of gamedata. 
* It saves the current gameBoard and reads it with the loadGame Method. 
*/ 

public class FileManagement { 
    static String filename = "Savegame.txt"; 

/** 
* Schema: 
* (0,0) | (0,1) | (0,2) 
* (1,0) | (1,1) | (1,2) 
* (2,0) | (2,1) | (2,2) 
*/ 
/** 
* @param gameBoard, the currently active Array from the Board.class. 
* @throws Exception, FileNotFoundException 
*/ 
public static void saveGame(int[][] gameBoard) throws Exception { 
    //serialization 
    PrintWriter writer; 
    try { 

     writer = new PrintWriter(new FileOutputStream(filename), false); 
     for (int i = 0; i < gameBoard.length; i++) { 
      for (int j = 0; j < gameBoard.length; j++) { 
       int entry = gameBoard[i][j]; 
       writer.print(entry); 
       writer.println('\n'); 
      } 

     } 
     writer.close(); 
    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } 
} 

/** 
* @throws Exception, FileNotFoundException 
*/ 
public static void loadGame() throws Exception { 
    //deserialization 
    FileReader fileReader = new FileReader(filename); 
    BufferedReader bufferedReader = new BufferedReader (fileReader); 
    try { 
     structurePack.Board.gameBoard[0][0] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[0][1] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[0][2] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[1][0] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[1][1] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[1][2] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[2][0] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[2][1] = Integer.parseInt(bufferedReader.readLine()); 
     structurePack.Board.gameBoard[2][2] = Integer.parseInt(bufferedReader.readLine()); 
     fileReader.close(); 
     bufferedReader.close(); 

    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } 
} 
} 

Readline API-документация

public String readLine() 
       throws IOException 

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. 

Returns: 
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

Throws: 
IOException - If an I/O error occurs 

See Also: 
Files.readAllLines(java.nio.file.Path, java.nio.charset.Charset) 
+2

Если вы читаете из файла, почему вы используете 'Scanner (System.in)'? – SomeJavaGuy

+0

попробуйте 'e.printStackTrace();' вместо 'System.out.println (e.getMessage());'.Это будет хорошей практикой в ​​отношении отображения исключений на консоли и, скорее всего, поможет вам. – Paul

+0

О, я думал, что могу использовать сканер ... мне нужно использовать BufferedReader? Https: //docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html – Dave

ответ

0

Пожалуйста, измените метод loadGame, как показано ниже:

public static void loadGame() throws Exception { 
    //deserialization 

    FileReader fileReader = new FileReader(filename); 
    BufferedReader bufferedReader = new BufferedReader(fileReader); 
    structurePack.Board.gameBoard[0][0] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[0][1] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[0][2] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[1][0] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[1][1] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[1][2] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[2][0] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[2][1] = Integer.parseInt(bufferedReader.readLine()); 
    structurePack.Board.gameBoard[2][2] = Integer.parseInt(bufferedReader.readLine()); 
} 

Этот код может работать для вас.

+0

Спасибо за ваш ответ. – Dave

+0

@ Давай сначала ответ был принят .. это его нет.? что-то не так? –

+0

Я все еще получаю исключение NullPointerException, но я снова заново запомню ваш ответ. Спасибо за ваши усилия. – Dave