I am a beginner in java. Ihave a string replacement code in which the user specifies the file path, the string to replace and the string to replace with. The code just works fine with .txt or .in files. But when I try to edit a .java file for which I intended to write the code, it somehow is unable to edit it. Can anybody suggest where actually the problem is? My code goes as follows:
import java.io.*;
import java.util.*;
public class StringReplace{
public static void main(String[] args) throws IOException
{
System.out.println("Enter path of file:");
Scanner sc=new Scanner(System.in);
String path=sc.nextLine();
File f=new File(path);
if (f.canRead())
{
System.out.print("Now enter the string to replace:_");
String oldString=sc.nextLine();
System.out.print("Now enter the string to replace with:_");
String newString=sc.nextLine();
StringBuffer sb=new StringBuffer();
sc=new Scanner(f);
sc.useDelimiter("");
while(sc.hasNext())
{
sb.append(sc.next());
}
sc.close();
FileWriter fw=new FileWriter(path);
PrintWriter pw=new PrintWriter(fw,true);
System.out.println(sb);
pw.println(sb.toString().replaceAll(oldString, newString));
fw.close();
pw.close();
System.out.print("DONE!");
}
else
System.out.println("File Does Not Exist");
}
}
}
Scanner
for this, to be honest - I'd useBufferedReader
and just read a line at a time, probably writing as I went.