java - 无法使用 java 程序编辑 .java 文件

标签 java string file replace edit

我是java初学者。我有一个字符串替换代码,用户在其中指定文件路径、要替换的字符串以及要替换的字符串。该代码适用于 .txt 或 .in 文件。但是,当我尝试编辑我打算为其编写代码的 .java 文件时,它不知何故无法编辑它。有人能指出问题到底出在哪里吗?我的代码如下:

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

最佳答案

正如注释所述,“.java”文件和任何其他文本文件之间应该没有区别。

我怀疑问题在于您没有意识到您的编辑器应用程序实际上是为执行正则表达式搜索/替换而编码的,而不是简单的字符串搜索/替换。 (这就是 String.replaceAll(...) 的作用...)如果无意中提供了包含正则表达式元字符的“要替换的字符串”,您可能会发现它不匹配或者在您不期望的位置匹配。

关于java - 无法使用 java 程序编辑 .java 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12120954/

相关文章:

java - 使 rJava 或 R 使用不同的(以前的)Java 版本

c++ - 比较两个字符串(但类型不同)

java - BufferedWriter:在文件关闭之前写入文件

java - 访问共享目录

c - stat.h 在 Linux 中不可用?

java - 在内存限制内对单词进行排序

Java 8 流 - 增量收集/部分减少/间歇映射/...这甚至叫什么?

c - qsort 反转字符串的顺序

java - 无法从数组中获取实际值,它只是显示 "NULL"

swift - AWS Polly - 突出显示特殊字符