我试图使用此代码删除包含随机数字和字母的文本文件中的所有字母
package textEdit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RemoveLetters {
public static void readFile(String file) {
try {
FileReader fis = new FileReader(file);
BufferedReader reader = new BufferedReader(fis);
FileWriter writer = new FileWriter(file);
BufferedWriter bwriter = new BufferedWriter(writer);
String line = null;
while ((line = reader.readLine()) != null) {
for (int i = 0; i < symbolsAndLetters.length; i++) {
String str = symbolsAndLetters[i];
str = str.replace(str, "");
}
}
reader.close();
bwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String[] symbolsAndLetters = {"A", "B", "C",
"D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
"Z", "=","a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",};
/**
* @param args
*/
public static void main(String[] args) {
readFile("c:/users/Kyle/workspace/Learn more java/src/music.txt");
}
}
问题是,它删除了文件中的所有内容,我对Java的阅读和写作都很陌生,所以任何人都可以帮我弄清楚我做错了什么吗?
答案 0 :(得分:1)
以下是您在while
循环中实际执行的操作(阅读评论):
// iterating over the items of your own static array (without fast enumeration)
for (int i = 0; i < symbolsAndLetters.length; i++) {
// initializing a new String and assigning it the value of your array
// that is currently indexed in your for-loop
String str = symbolsAndLetters[i];
// replacing the String's content by replacing its value
// (1st parameter, the "str" value itself)
// with an empty String
str = str.replace(str, "");
}
这完全没有任何结果。
这是你想要做的。
StringBuilder
并将原始内容替换为
原始读者关闭后toString
的{{1}}表示。 StringBuilder
数组使用正则表达式:
String
答案 1 :(得分:1)
我会创建一个新文件来写输出。在这里,我只需附加“#34; new&#34;它 - FileWriter writer = new FileWriter(file +&#34; new&#34;);
然后使用正则表达式替换您想要的字符 - line = line.replaceAll(&#34; [a-zA-Z]&#34;,&#34;&#34;);
然后将其附加到新文件:
- bwriter.append(第+&#34; \ n&#34;);
答案 2 :(得分:0)
在while
循环内部,在for
循环之后,您应该将该行写回文件。
当循环进入下一行时,它会丢失str
中的所有内容。
您已经打开了文件输出流,但从不写任何内容。它不会覆盖所有内容,它不会写任何内容。