如何在JAVA中搜索和替换文本文件中的字符串? [英] How to search and replace a string in a textfile in JAVA?

查看:446
本文介绍了如何在JAVA中搜索和替换文本文件中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,情况就是这样。我的目标是在搜索该学生然后输入标记后,我将在文本文件中编辑学生的标记。现在,一切正常,但我正在阅读学生成绩的原始文件由于某种原因没有被删除。所以,我有一个更新的文本文件与学生的新成绩,原始文件仍然挂在那里由于某种原因。我能做错什么?请帮帮我!谢谢



So, here is the situation. My goal is that i am going to edit the marks of a student in a text file after searching for that student and then entering the marks. Now, everything works fine but the original file from which i was reading the grade of the student doesn't gets delete for some reason. So, i have an updated text file with the new grade of the student and the original file is still hanging there for some reason. What could i be doing wrong. Please help me out! Thanks

package gerard;
import java.io.*;      
import java.util.*;
import java.util.Scanner;

public class trial {
	public static void main(String args[]) throws IOException
	{
		File f = new File("saw.txt");
		File ki = new File("Textsave.txt");
		Scanner pi = new Scanner(System.in);
		
		
		 FileWriter fn = new FileWriter(f);
		 FileReader fr = new FileReader(ki);     
		 BufferedReader br = new BufferedReader(fr);   
		 String line = null;
		 String delete;
		 System.out.println("Enter the name of the student you want to replace");
		 delete = pi.nextLine();
		 
		 while((line = br.readLine()) != null)
		 {
			 
			 boolean retval = line.contains(delete);
			 
			 if(retval == false)
			 {
				 fn.write(line);
				 fn.write(System.getProperty( "line.separator" ));
				 

				// System.out.println("     " +retval);
				 

			 }
			 
			 
			 if(retval==true)
			 {
				 String num,jum;
				 System.out.println(line);
				 System.out.println("Enter the number you want to replace");
				 num = pi.nextLine();
				 System.out.println("Enter the number you want to replace with");
				 jum = pi.nextLine();
				
				 String jam;
				 jam = line.replaceAll(num,jum );
				 
				 System.out.println(jam);

				 fn.write(jam);
				 fn.write(System.getProperty( "line.separator" ));
                 
			 }
			 
			 
			 
			 
			
		 }
		 
		br.close(); //This is where the problem is, i dont know why the 
                              //original file "Textsave.txt" doesnot get deleted.
		fn.close();
		ki.delete();
		f.renameTo(ki);
		 
		
		 
		 
		 
	}

}

推荐答案

我怀疑问题可能是你仍然有一个连接到该文件的文件对象,因此无法删除。请查看 http://docs.oracle.com/javase/7/ docs / api / java / io / BufferedReader.html [ ^ ]了解玩具如何创建读者的示例。
I suspect the issue may be that you still have a File object connected to the file, so it cannot be deleted. Take a look at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html[^] for an example of how toy create your reader.


这篇关于如何在JAVA中搜索和替换文本文件中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆