I am making a text based game for my programming class, and am working on the saving system at the moment, however, when I run the save method, it overwrites the file, but doesn't insert the new data, it leaves the file blank.

Here is the whole save class.

package character;

//
//  charSaveHandler.java
//  main
//
//  This file deals with saving the character
//

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

public class charSaveHandler {
	
	/* Create any needed objects */
	
	
	/* Assign needed variables */
	private Formatter saveChar;
	//public Scanner openChar;
	
	public charSaveHandler(String charName, int charLevel, int charExp){
		try{
			File exist = new File("characters/" + charName + ".txt");
			if(exist.exists()){
				saveChar = new Formatter("characters/" + charName + ".txt");
				saveChar.format("%s%s%s", charName, charLevel, charExp);
			}
			else{
				System.out.println("Can not save character. It does not exist.");
			}
		}
		catch(Exception e){
			System.out.println("Unable to find character " + charName);
			
		}
	}
	
	public void openChar(String charName){
		try{
			saveChar = new Formatter("characters/" + charName + ".txt");
		}
		catch(Exception e){
			//System.out.println("");
		}
	}
	
	public void saveToDB(String charName, int charLevel, int charExp){
		try{
			saveChar.format("%s%s%s", "d", " 50 ", "0");
			System.out.println("Character " + charName + " saved!");
		}
		catch(Exception e){
			System.out.println("Cannot save character " + charName);
		}
		
	}
	
}

It also outputs the it has saved the character.

Recommended Answers

All 5 Replies

Did you open your file in the append mode? If you just open to write, by default it is overwritten mode.

I opened it the same way I did in my create character file.

This code here doesn't actually open or write to a file, so it's hard to say what your error might be. It's very possible that it's something to do with the file mode, as Taywin suggests, or some other error, but here all you do is identify a file and create an object associated with it.
Writing to the file involves some other steps - have you taken those elsewhere?
If not, that's why nothing's happening.

If makes a new file with the same name (overwrites in same directory), but doesn't insert the text I want it to (it does nothing).

I basically copy/pasted from my createChar file, which works as intended.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.