替换文件中的多个字符



我想将文本文件中的土耳其字符{ 'ç', 'Ç', 'İ', 'ı', 'Ğ', 'ğ', 'Ş', 'ş' }替换为新的英文字符{ 'c', 'C', 'I', 'i', 'G', 'g', 'S', 's' }

这是我的代码。我在控制台上只得到原始内容而没有更改,并且它不会创建新文件。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Replace {
String line = null;
String ret = null;
public void doIt() {
try {
File f1 = new File("C:\Users\PC\Desktop\new-words2.txt");
FileOutputStream fop = new FileOutputStream(f1);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(new 
FileReader("C:\\Users\\PC\\Desktop\new-words.txt"));
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
char[] turkishChars = new char[] { 'ç', 'Ç', 'İ', 'ı', 'Ğ', 'ğ', 'Ş', 'ş' };
char[] englishChars = new char[] { 'c', 'C', 'I', 'i', 'G', 'g', 'S', 's' };
for (int i = 0; i < turkishChars.length; i++) {
ret = ret.replaceAll(new String(new char[] { turkishChars[i] }),
new String(new char[] { englishChars[i] }));
out.write(ret);
}
}
fr.close();
br.close();
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
Main1 fr = new Main1();
fr.doIt();
}
}

编辑:

这是为我工作的新代码。但是我想为replace方法使用更短的代码。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Replace {
String line = null;
String ret = null;
public void doIt() {
try {
File f1 = new File("C:\Users\PC\Desktop\new-words2.txt");
FileOutputStream fop = new FileOutputStream(f1);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(new 
FileReader("C:\Users\PC\Desktop\new-words.txt"));
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
ret = line.replace("ç", "c").replace("Ç", "C").replace("İ", "I").replace("ı", "i").replace("Ğ", "G")
.replace("ğ", "g").replace("Ş", "S").replace("ş", "s");
out.write(ret + "n");
}
fr.close();
br.close();
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
Replace fr = new Replace();
fr.doIt();
}
}

我对这个主题知之甚少,但它可以是你的程序不检测br FileReader路径由于4反斜杠?将它们改为两个(FileReader("C:\Users\PC\Desktop\new-words.txt"))再试一次。也许这有帮助。

相关内容

  • 没有找到相关文章

最新更新