繁体   English   中英

使用Java替换文件中的文本

[英]Replacing text in a file using java

我有一个名为FormatString.java的文本文件。 它包含一些单词。 在所有这些单词中,我想将单词oldstring替换为newstring,并将最终结果重命名为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

尝试像上面一样用相同的目录中的所有文件运行该程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM