Saving Game Data

So, I’m trying to make a folder for my game in the C: drive that stores an int for now. I want to be able to do something like this.

if(level == 1)

change lvl to 1 in the file

http://i.minus.com/ibgap73YQcAn4Q.gif

and so on. I’m not sure how to get the scanner to scan this level variable and use it. This is the code I have so far:

public class DirectoryMaker {
	
	
	static BufferedWriter bw;
	static int lvl = 1;
	static int hp = 100;
	
	public static void main(String[] args) throws IOException {
		
		
		FileWriter fw;
		
		
		
		File dir = new File("c:\\MyFile\\b\\stuff");
		if (!dir.exists()) {
			if (dir.mkdirs()) {
				System.out.println("Directory is created!");
			} else {
				System.out.println("Failed to create directory!");
			}
		
		}
		
		
		
		
		String fileName="hi";
		File tagFile=new File(dir,fileName+".txt");
		if(!tagFile.exists()){
		try {
			
			
			
			fw = new FileWriter(tagFile.getAbsoluteFile());
			bw = new BufferedWriter(fw);
			bw.write("LEVEL: " + lvl + "\n");
			
			
			tagFile.createNewFile();
			bw.close();
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		}
		
		
		Scanner s = new Scanner(tagFile);
		while(s.hasNextLine()) {
			System.out.println(s.nextLine());
		
		}
		System.exit(1);
	}
}

Hopefully I make some sense.

PS: again to be clear, I need to (when the save button is pressed or something) save the x, y, and level in a folder I made. when the game starts (boolean started = true), I need to scan this folder for the level, x, and y.

Since you’re just storing key : value pairs, why not make life easy and use either Preferences or Properties?

Alternatively, you could consider using Java’s built-in serialization.

Here’s a nice to-the-point example:

The simplest way to do this is to write it to a text file; I built this for my encryption programs,basic but it works.


public static String readstring(String location) throws IOException {
		File file = new File(location);

		if (!file.exists()) {
			return null;
		}
		FileReader fr = new FileReader(file.getAbsoluteFile());
		BufferedReader br = new BufferedReader(fr);
		String filedata = br.readLine();
		return filedata;
	}

and for writing the value:


public static void writestring(String content) throws IOException {
		File file = new File("unencrypted.txt");
		if (!file.exists()) {
			file.createNewFile();
		}

		FileWriter fw = new FileWriter(file.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(content);
		bw.close();

	}