Please I would like your help with the following issue:
This is a sample code customized solely for clarifying my question:
File accounts_File = new File("Sample_Folder\\example.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String str_String = ""; //For storing the input from the file.
fis = new FileInputStream(accounts_File);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0)
{
str_String = dis.readLine(); //Reading the line from the file.
StringTokenizer st = new StringTokenizer(str_String);
while (st.hasMoreTokens())
{
//I need some help here
}
}
fis.close();
bis.close();
dis.close();
The Input File (example.txt) looks as follows: James>Hector>AUS>25
The Objective is simply scanning and replacing “Hector” with “Anderson”. The problem is that the name “Hector” is not known; the only thing known is its location (after the first “>“).
Note: I can change the format of the input file if that makes it easier. As an example I can change the format to something like:
FirstName: James
LastName: Hector
Country: AUS
Age: 25
*Where the program now will scan for the keyword “LastName:” and replace everything following it with “Anderson”.
Thanks in advance for your help!
Any Suggestions are greatly appreciated.
Keep the format, it looks like a standard csv file (comma separated values, where the “comma” is the “>” char) and csv files are easy to read and write!
As you can’t replace file content “on the disk”, you’ll have to read the file into memory, rewrite it in memory with the changes needed and rewrite it to the disk.
A simple model for the file is a two dimensional string array, each line of the file is a row, each value a column, which makes 4 columns. The last name (the string, you want to replace) now is always at
matrix[lineNumber][1]. Change the value on the second column for each row and your done.For production code, I’d code a class to represent a record. Then, your code could look like this:
Note, that the actual work (file IO, changing names) is done in different methods and classes. This keeps the main algorithm inside the replace method readable.