【问题标题】:PrintWriter does not write to specified filePrintWriter 不写入指定文件
【发布时间】:2015-04-08 12:53:02
【问题描述】:

我有一个程序必须在文件中读取多个内容,例如文件中有多少元音等。出于测试目的,我刚刚将结果打印到控制台,但是我需要将其打印到单独的文件,所以我正在使用 Print Writer。我将包含我的整个代码,这样你就可以确切地看到它在做什么。

   //Variables
    int vowels = 0, digits = 0, spaces = 0, upperCase = 0, lowerCase = 0;
    char ch;

    // Creates File Chooser and Scans Selected file.
    Scanner in = null;
    File selectedFile = null;
    JFileChooser chooser = new JFileChooser("E:/OOSD/src/textAnalyser");
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
        in = new Scanner(selectedFile);
    }

    //Loops through the file until it has counted everything. 
    while (in.hasNext()) {
        //Gets the next line from the input
        String line = in.nextLine();
        // loop goes on till it has no next line.
        for (int i = 0; i < line.length(); i++) {   
            ch = line.charAt(i);
    if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i'
    || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') {
                vowels++;
            } else if (Character.isDigit(ch)) {
                digits++;
            } else if (Character.isWhitespace(ch)) {
                spaces++;
            } else if (Character.isUpperCase(ch)) {
                upperCase++;
            } else if (Character.isLowerCase(ch)) {
                lowerCase++;
            }
        }
    }//Ends While Loop.

    PrintWriter writer = new PrintWriter("Output.txt", "UTF-8");
    writer.println("Vowels: " + vowels);
    writer.println("Digits : " + digits);
    writer.println("Spaces : " + spaces);
    writer.println("Capital Letters : " + upperCase);
    writer.println("LoweCase : " + lowerCase);
    writer.close();

如果您能告诉我为什么它不会打印到指定的输出文件,那将非常感谢 :) 抱歉,这是一个很长的问题。

【问题讨论】:

  • 它应该写入指定的文件。如果没有,你可能做错了什么。是否产生错误信息?您确定要在正确的目录中查找文件吗?

标签: java output printwriter


【解决方案1】:

您的 PrintWriter 已禁用自动刷新。在构造函数中启用它,或者在编写器关闭之前手动刷新。既然你读了行,你应该使用in.hasNextLine()而不是in.hasNext()

【讨论】:

  • 对此进行扩展 - 默认情况下,PrintWriter 会将内容存储在内存中,而不是实际将它们刷新(即写入)到磁盘上的文件,直到您通过调用 writer.flush() 明确告知它。启用自动刷新意味着编写器将在您进行时刷新/写入文件,而无需显式调用。
【解决方案2】:

为了让您的程序正常工作,您需要在关闭之前刷新 PrintWriter。

    PrintWriter writer = new PrintWriter("C:/Users/r7h8/Output.txt", "UTF-8");
    writer.println("Vowels: " + vowels);
    writer.println("Digits : " + digits);
    writer.println("Spaces : " + spaces);
    writer.println("Capital Letters : " + upperCase);
    writer.println("LoweCase : " + lowerCase);
    writer.flush();
    writer.close();

当你刷新它时,内容被写入文件。

最好的问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多