[英]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 苹果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. 现在,每当我得到一个整数值时,我都必须将其计数增加1并再次保存回同一文件。
For example, if I read some content like above I should be able to save 例如,如果我阅读上述内容,则应该可以保存
Apple 2 4 6 苹果2 4 6
back to the same file again 再次回到同一文件
My code looks like 我的代码看起来像
try{ FileWriter fstream = new FileWriter("c:\\Apple.txt",true); 试试{FileWriter fstream = new FileWriter(“ c:\\ Apple.txt”,true);
FileReader inputFileReader = new FileReader("c:\\Apple.txt");
BufferedReader inputStream = new BufferedReader(inputFileReader);
PrintWriter outputStream = 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 苹果1 3 5苹果1 4 5
But my required output is 但是我需要的输出是
Apple 1 4 5 苹果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 您不能在同一个文件上进行交互操作(或者至少可以,但是这确实很棘手)..您可以
我使用RandomAccessFile,它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.