Skip to content
Advertisement

How can I update specific parts of a text file in java?

This program is supposed to take in user input about a players name, assists, games played, scores, etc and print it in a .txt file. When the updateData(); method is called I want to be able to ask the user for the players name and what data they want to update, then i should be able to edit that specific part of the text. how could i go about doing this?

Main Class

JavaScript

Reader Class

JavaScript

Text File Format:

Name GP G A P S S%

Bobby 2 3 6 14 7 50

George 1 3 14 2 9 23

So if the user wanted to edit Name: George, type: Assists, the value 14 beside Georges name only would be edited

I have tried using an if statement to locate the string in the text and append it but I could not figure out how to only change the specified number without changing all the numbers found. Ex: if in the example above 14 is appended both would be changed instead of the one

Advertisement

Answer

If you are allowed for this project (i.e., not a school assignment), I recommend using JSON, YAML, or XML. There are too many Java libraries to recommend for using these types of files, but you can search “Java JSON library” for example.

First, need to address some issues…

It’s not good practice to put Scanner scan = new Scanner(System.in); in a try-with-resource. It will auto-close System.in and won’t be useable after being used in your Reader class. Instead, just do this:

JavaScript

Or, even better, don’t pass it to the constructor, but just set scan to it in the constructor as this.scan = new Scanner(System.in);

Next, for fileReader, you can just initialize it similarly as you did for fileWriter:

JavaScript

Next, this line:

JavaScript

Every time this program is run, this line will overwrite the file to empty, which is probably not what you want. You could add StandardOpenOption.APPEND, but then this means you’ll only write to the end of the file.

When you update data, you also have the issue that you’ll need to “push” down all of the data that comes after it. For example:

JavaScript

If you change the name Bobby to something longer like Mr. President, then it will overwrite the data after it.

While there are different options, the best and simplest is to just read the entire file and store each bit of data in a class (name, scores, etc.) and then close the fileReader.

Then when a user updates some data, change that data (instance variables) in the class and then write all of that data to the file.

Here’s some pseudo-code:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement