I would like to replace data in a file with some new data and rename the file with a different name in java. I have the old file saved in the same class directory as the code to carry out the changes is saved. The command that I use in the command prompt is as below.
java ReplacingText oldfile newfile oldstring newstring
I get the error:
Exception in thread "main" java.lang.NoClassDefFoundError: ReplacingText (wrong name: replacingtext/ReplacingText)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Could someone shed some light on it.
package replacingtext;
import java.io.*;
import java.util.*;
public class ReplacingText
{
public static void main(String[] args) throws Exception
{
if (args.length !=4)
{
System.out.println(
"Usage: java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(0);
}
File sourceFile = new File(args[0]);
if(!sourceFile.exists())
{
System.out.println("Source file " + args[0]+" does not exist");
System.exit(0);
}
File targetFile = new File(args[1]);
if (targetFile.exists())
{
System.out.println("Target File " + args[1] + "already exist");
System.exit(0);
}
Scanner input = new Scanner(sourceFile);
PrintWriter output2 = new PrintWriter(targetFile);
while (input.hasNext())
{
String s1=input.nextLine();
String s2=s1.replaceAll(args[2],args[3]);
output2.println(s2);
}
input.close();
output2.close();
}
}
C:\projects\replacingtext\ReplacingText.class, you mustcdtoC:\projectsand type the following:java replacingtext.ReplacingText oldfile newfile oldstring newstring