How to read and modify a text file based on some condition
How can I read an existing text file and modify some of its value based on some condition like if I get some text like
Apple 1 3 5
Now, here whenever I get an integer value I have to increase its count by 1 and save back to the same file again.
For example, if I read some content like above I should be able to save
Apple 2 4 6
back to the same file again
My code looks like
try{ FileWriter fstream = new FileWriter("c:\Apple.txt",true);
FileReader inputFileReader = new FileReader("c:\\Apple.txt");
BufferedReader inputStream = new BufferedReader(inputFileReader);
PrintWriter outputS开发者_开发技巧tream = new PrintWriter(fstream);
while((inline=inputStream.readLine())!=null)
{
values=inline.split("-");
Integer l = Integer.parseInt(values[2])+1;
outputStream.print((inline.replaceAll(values[2],l.toString())));
}
outputStream.close();
}
So, I get an output like
Apple 1 3 5 Apple 1 4 5
But my required output is
Apple 1 4 5
Thanks in advace
Split your code into separate method calls:
File f = getFile();
String text = getFileContents(f);
if(matchesRequirements(text)){
String newText = performReplacements(text);
writeFile(newText, f);
}
Now you can implement these methods:
private static void writeFile(String newText, File f){
// TODO implement this method
}
private static String performReplacements(String text){
// TODO implement this method
return null;
}
private static boolean matchesRequirements(String text){
// TODO implement this method
return false;
}
private static String getFileContents(File f){
// TODO implement this method
return null;
}
private static File getFile(){
// TODO implement this method
return null;
}
See how far you get and ask specific questions where you have problems.
You can't do it interactively on the same file (or at least maybe you can but it would be really tricky).. you could
- open the input file
- open the output file
- for each line in file
- check your condition, if true
- generate the new line according to what you are going to modify
- save it on output file
- if false
- copy the line into new file without modifying it
- check your condition, if true
- close both files
- delete first one and rename second one to first (you can do it easily with API functions)
I used RandomAccessFile and it works fine.
精彩评论