PrintWriter不会写入指定的文件

时间:2015-04-08 12:53:02

标签: java output printwriter

我有一个程序,必须读取文件计算多个东西,如文件中有多少元音等。为了测试目的我刚刚将结果打印到控制台但是我需要将它打印到一个单独的文件,所以我使用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();

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

2 个答案:

答案 0 :(得分:2)

您的PrintWriter已禁用autoflush。在构造函数中启用它,或在关闭编写器之前手动刷新。由于您阅读了行,因此您应该使用in.hasNextLine()而不是in.hasNext()

答案 1 :(得分:0)

要使您的程序正常工作,您需要在关闭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();

刷新时,内容将写入文件。

最好的问候。