私はJavaにかなり慣れていないので、データをファイルに読み書きするための2つの小さな関数を作成しました。書き込まれるデータは、ゲーム内のマップ上のキャラクターのx座標とy座標です。ファイルに書き込まれたデータは問題ないようです。
234
-123
次のコードでデータを書き込みます。
public void save(int x, int y)
{
try
{
FileWriter fstream = new FileWriter("skygrim.txt"); //Create save-file
BufferedWriter out = new BufferedWriter(fstream); //New writer, connected to save-file
out.write(x + "\n" +y); //Write position to file
out.close(); //Close file
}catch (Exception e){System.out.println("Error: " + e.getMessage());}
}
後でデータを読み取りたいときに、保存したゲームを「ロード」できるようにするために、ファイルから次の値を取得します。
50
51
次のコードを使用してファイルから読み取ります。
public int[] read(String file)
{
int[] coordinates = new int[2];
try
{
FileReader fstream = new FileReader(file);
BufferedReader in = new BufferedReader(fstream);
coordinates[0] = in.read();
coordinates[1] = in.read();
in.close();
}catch(Exception e){System.out.println("Error" + e.getMessage());}
System.out.println("x: " + coordinates[0]);
System.out.println("y: " + coordinates[1]);
return coordinates;
}
プログラムがファイルをひどく間違って読み取るのはなぜですか、そしてそれについて何ができますか?