1
저는 java의 초보자입니다. 사용자가 파일 경로, 바꿀 문자열 및 바꿀 문자열을 지정하는 문자열 바꾸기 코드가 있습니다. 이 코드는 .txt 또는 .in 파일과 잘 작동합니다. 그러나 내가 코드를 작성하고자하는 .java 파일을 편집하려고하면 그것을 어떻게 든 편집 할 수 없습니다. 아무도 실제로 문제가있는 곳을 제안 할 수 있습니까? 다음과 같이 내 코드는 간다 :java 프로그램을 사용하여 .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 파일에는 유니 코드 문자가 포함될 수 있습니다. –
나를 위해 코드 .java 파일에서 잘 작동합니다. – Vinesh