使用java替换文件中的文本
我有一个名为FormatString.java的文本文件。它包含了几个单词。在这些单词中,我想用newstring替换单词oldstring,并将最终结果重命名为t.txt。我已经写了代码。从技术上讲,这应该是可行的。问题是我不知道在哪里保存FormatString.java文件。我是将其保存在保存程序ReplacingText的同一类文件夹中,还是将其保存在其他地方。 我转到命令提示符并进入保存ReplacingText.class和FormatString.java文件的文件夹,然后键入以下语句: java ReplacingText FormatString.java t.txt旧字符串新闻字符串使用java替换文件中的文本,java,Java,我有一个名为FormatString.java的文本文件。它包含了几个单词。在这些单词中,我想用newstring替换单词oldstring,并将最终结果重命名为t.txt。我已经写了代码。从技术上讲,这应该是可行的。问题是我不知道在哪里保存FormatString.java文件。我是将其保存在保存程序ReplacingText的同一类文件夹中,还是将其保存在其他地方。 我转到命令提示符并进入保存ReplacingText.class和FormatString.java文件的文件夹,然后键入以下
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
文件夹中
日蚀
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
试着像上面一样运行程序,让所有文件都像我一样位于同一目录中