使用java替换文件中的文本

我有一个名为FormatString.java的文本文件。 它包含几个字。 在这些单词中,我想用newtring替换oldstring这个单词,并将最终结果重命名为t.txt。 我写了代码。 从技术上讲,它应该工作。 问题是我不知道在哪里保存FormatString.java文件。 我是否将其保存在保存程序ReplacingText的同一类文件夹中,或者将其保存在其他位置。 我转到命令提示符并进入保存ReplacingText.class和FormatString.java文件的文件夹,并键入以下语句:

java ReplacingText FormatString.java t.txt oldstring newstring

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(); } } 

如果从命令行运行程序,也许你想将FormatString.java放在bin文件夹中。

用Eclipse

 ProjectRootFolder bin FromatString.java ReplacingText.class src ReplacingText.java 

有了Netbeans

 ProjectRootFolder build classes FromatString.txt replacinttext ReplacingText.class src ReplacingText.java 

C:\Users\Dhaval\Desktop\Java Assignment\ReplacingText\build\classes>java replacingtext.ReplaceText FormatString.java public private

尝试像我一样运行程序,像我一样运行相同Directorys中的所有文件