Skip to content
Sign upLog in
← Back to Community

How to create a file in java and save the data inside the file and get data when code starts again

Profile icon
softwarenginner

I would like to create a file and if it is the first time opening or running the code it will create a file then when the user enters data when user click on a button I want to save the data inside the text file. When the program starts again I want to get the data from the text file and just keep going where left of last time. By the way guys this is not a android program it is java with JPanel and JFrame Thank you

Voters
Profile icon
softwarenginner
Comments
hotnewtop
Profile icon
SixBeeps

First, import java.io.* and java.util.*

Getting a file's contents

File myFile = new File("path/to/file.txt"); Scanner fileReader = new Scanner(myFile); String fileContents = ""; // File contents will be stored in here while (fileReader.hasNextLine()) fileContents += fileReader.nextLine();

Setting a file's contents

Note: This will create the file if it doesn't already exist

FileWriter fileWrite = new FileWriter("path/to/output.txt"); fileWrite.write("Here are some file contents!");
Profile icon
softwarenginner

@SixBeeps
Well when you want to get the data so let's say I run the program again so when I run it I want to get the data and write auto.

Profile icon
SixBeeps

@softwarenginner
I'm a little confused. What are you looking for?

Profile icon
softwarenginner

@SixBeeps
So if it is the first time running the code. It is going to create a text file and let's say the program is asking for my name so I would just write my name and it is going to save my name into the text file. And later everytime I run my code it is going to write my name to screen by reading my text file.

Profile icon
SixBeeps

@softwarenginner
Ah, then I'll add the last missing bit.

Checking if a file exists

File myFile = new File("path/to/file.txt"); if (myFile.exists()) { // Do stuff if the file exists } else { // Do stuff if it doesn't }
Profile icon
JooChoi

@SixBeeps
How do I use this code in my code?

Profile icon
SixBeeps

@JooChoi
Try using the clipboard (Select the code and hit Ctrl + C to copy, then go into your code and hit Ctrl + V to paste)

Profile icon
JooChoi

@SixBeeps
How do I(or my code) remember how much money I have and hp I have? Also, yours didn't work for me. Also, when you save it, it has to show the next time you play. How do you do that?

Profile icon
JooChoi

@SixBeeps
Did you read my comment?