【发布时间】: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