我不知道为什么我正在写入的文件是空白的。我正在替换某些字符,然后写出新的转换后的文件。它应该包含我正在导入的文件中的所有行。然而,当我打开它时,它完全是空白的。谢谢。
//this method find the number of occurrences of a character find in a string l
public static int numberOccurances(String l, char find){
int count=0; //sets the number of occurrences to 0
for(int x=0; x<l.length();x++){ //searches throughout the string adding one to count
if(l.charAt(x)==find)
count++;
}
return count;
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
File file = new File("new.txt");
Scanner scanner = new Scanner(file);
PrintWriter writer = new PrintWriter("new.txt", "UTF-8");
while(scanner.hasNextLine()){
String line = scanner.nextLine();
for(int y=0; y<line.length(); y++){
if(line.charAt(y)=='M')
line=line.substring(0,y) + 'm' + line.substring(y+1);
if(line.charAt(y)=='m')
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
int numberm=numberOccurances(line, 'm');
int numberM = numberOccurances(line, 'M');
line=line + "%:m" + numberm + ":M" + numberM + ":";
writer.println(line);
}
writer.close();
}
最佳答案
您正在写入正在读取的同一个文件(“new.txt”,根据您的示例)。 PrintWriter
truncates existing files to 0 bytes on opening 。因此,一旦您打开它,您就会删除其中的数据,并且您的扫描仪
将无法读取任何内容。
当输入和输出文件相同时,传统方法是将输出写入新的临时文件,然后在所有处理完成后用临时文件替换原始文件。
另一种方法(尽管在您的情况下不太方便)是在打开输出之前将输入文件完全加载到内存中,处理数据,然后将处理后的数据写出。
关于java - 为什么文件被写入空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313269/