为什么文件被写入空白?

时间:2014-03-10 23:07:46

标签: java printwriter

我不知道为什么我写的文件是空白的。我正在替换某些字符,然后写出新转换的文件。它应该包含我导入的文件中的所有行。但是,当我打开它时,它完全是空白的。感谢。

//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();
}

1 个答案:

答案 0 :(得分:3)

您正在写入您正在阅读的同一文件(“new.txt”,根据您的示例)。 PrintWriter truncates existing files to 0 bytes on opening。因此,只要您打开它,就会删除其中的数据,而您的Scanner无需阅读。

传统方法,当输入和输出文件相同时,将输出写入新的临时文件,然后在完成所有处理后将原始文件替换为临时文件。

另一种方法虽然在您的情况下不太方便,但是在打开输出之前将输入文件完全加载到内存中,处理数据,然后将处理后的数据写出来。