1. Use a database to store the info
2. If it has to be flat file based use an XML format - Java has built in support for parsing, editing and saving XML files.
3. If it has to be a simple text file do either:
3a. Use java.io.RandomAccessFile but you have to be careful as you can only overwrite and not insert. ie the new data must be exactly the same length as the data you are replacing
3b. Use the type of technique you are currently using but do it as follows:
Open a Reader
Open a Writer to a temp file
Read in each line and write it to the temp file until you get to the line you want to edit.
Write the new data to the temp file.
Read in the remaining lines and write them to the temp file.
Delete the original file or rename it to .bak
Rename the temp file to the original file name.
Just copied this directly from my framework's text reader.
Using a FileReader, you can read in each line to return a string array. Using the line number - 1, you can use it as the indexer to change the specified line of the array. Then use a FileWriter object to write the array back into the file. =)
Code:
public String[] ReadFileLines(String filepath) throws FileNotFoundException, IOException {
this.ValidateFilePath(filepath);
ArrayList<String> lines = new ArrayList<String>();
java.io.FileReader reader = new java.io.FileReader(filepath);
java.io.BufferedReader buffer = new java.io.BufferedReader(reader);
String line = null;
while ((line = buffer.readLine()) != null) {
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
}
Now... what logic you are going to use to determine which line you want is a completely different question.
Bookmarks