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

时间:2012-08-25 09:54:39

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

1 个答案:

答案 0 :(得分:1)

正如评论所述,“。java”文件与任何其他文本文件之间应该没有区别。

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