【问题标题】:Why is the file being written to blank?为什么文件被写入空白?
【发布时间】:2014-03-11 07:17:38
【问题描述】:

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

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

【问题讨论】:

    标签: java printwriter


    【解决方案1】:

    您正在写入您正在读取的同一文件(“new.txt”,根据您的示例)。 PrintWriter truncates existing files to 0 bytes on opening。因此,你一打开它,里面的数据就被抹掉了,你的Scanner就没有什么可读的了。

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

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

    【讨论】:

    • 谢谢,但即使我写入不同的文件,该文件仍然是空白的。是否还有其他可能是空白的?
    • @user2825125 看起来不错...但我会更仔细地查看。我建议你在里面放一些临时的调试打印输出,或者在调试器中运行你的代码,这样你就可以跟踪正在发生的事情。您确定您的输入文件包含数据吗?有没有可能,因为你用以前运行的空白文件覆盖了它,现在它是空白的?
    • 是的,这就是问题所在。感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2013-06-13
    相关资源
    最近更新 更多