【问题标题】:Cannot edit a .java file with a java program无法使用 java 程序编辑 .java 文件
【发布时间】:2012-08-25 09:54:38
【问题描述】:

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

【问题讨论】:

  • 那么它做什么呢?老实说,我不会为此使用Scanner - 我会使用BufferedReader,一次只读一行,可能边写边写。
  • 谁知道二进制或文本流的实际问题。 Java 文件可能包含 unicode 字符。
  • 对我来说,代码在 .java 文件中也可以正常工作。
  • @Jon Skeet:我在这里使用带有空白字符串作为分隔符的扫描仪,因为我需要在编辑的文件中保留扫描仪和 bufferedReader 的所有默认分隔符。只有“oldString”会被改变。
  • 你得到的错误是什么?

标签: java string file replace edit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 2012-06-21
    • 2012-09-25
    • 2020-12-10
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多