I've been able to write a program to read and write files, however, I've been unable to edit already written files. I've been writing files using the Formatter class, but this creates an entirely new file and so I haven't been able to use this to edit a file rather than rewriting it completely -- is it even possible to do so using the Formatter class?
I've posted up what I currently have; and I've added some comments to try and explain what the program is supposed to do. But basically what I want to be able to do is; write to already existing files using the same functionality that the Formatter class gives; like going to the next line of a file and so on.
Any help is much appreciated :)
Code:/* This program allows users to read a database and find an entry by entering "ID" followed by their ID number (01 - 05 using the default database; example: ID01)
* Entering "ID" on its on will print out the entire list of entries on the database. */
import java.util.Scanner;
public class RunUserDatabase {
public static void main(String[] args) {
int counter = 0;
UserDatabase database = new UserDatabase();
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
database.createDatabase(); // Added this method so that if someone else runs the program in order to test it they'll have a database to do so with.
if (userinput.equals("ID")) {
database.readFile();
}
while(true) {
if (userinput.equals("ID0"+ counter)) {
database.findUser(Integer.toString(counter));
break;
}
counter++;
}
}
}
Code:import java.io.File;
import java.util.Formatter;
import java.util.Scanner;
public class UserDatabase {
File file = new File("/* Can be used if a database already exists; rather than creating a new database*/");
Scanner filescanner;
Formatter fileformatter;
public void createDatabase() {
file = new File("UserDatabase.txt");
try {
fileformatter = new Formatter(file);
}
catch(Exception e) {}
fileformatter.format("%s\n%s\n%s\n%s\n%s", "01 First Person", "02 Second Person", "03 Third Person", "04 Fourth Person", "05 Fifth Person");
fileformatter.close();
}
/* Prints out all of the contents of the file to the screen */
public void readFile() {
try {
filescanner = new Scanner(file);
}
catch (Exception e) {
System.out.println("File not found");
}
while (filescanner.hasNextLine()) {
System.out.println(filescanner.nextLine());
}
filescanner.close();
}
/* Prints a specific users information trough the given idNumber */
public void findUser(String idNumber) {
try {
filescanner = new Scanner(file);
}
catch (Exception e) {}
for (int i = 1; i < Integer.parseInt(idNumber); i++) {
filescanner.nextLine();
}
System.out.println(filescanner.nextLine());
filescanner.close();
}
}

