java - 为什么文件被写入空白?

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

最佳答案

您正在写入正在读取的同一个文件(“new.txt”,根据您的示例)。 PrintWriter truncates existing files to 0 bytes on opening 。因此,一旦您打开它,您就会删除其中的数据,并且您的扫描仪将无法读取任何内容。

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

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

关于java - 为什么文件被写入空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313269/

相关文章:

java - Wildfly 9 的standalone.xml 文件中的host 标记中的default-web-module 属性的用途是什么?

java - 无法运行 WordCount-Compiler 问题的 java 示例

Java 扫描仪抛出 NoSuchElementException : No Line Found

java - 将对象写入文本文件的最佳方法

java - 读/写文件不会写入输出

java - Java 中的 PrintWriter 和 FileOutputStream

java - Berkeley DB JE - 打开游标计数

java - QueryDSL 排序不适用于 Spring Data

java - ImageButton 背景颜色更改 onClick

java - Filewriter-Printwriter 无法在 Linux 上使用 jar