簡體   English   中英

PrintWriter不寫入指定的文件

[英]PrintWriter does not write to specified file

我有一個程序必須讀取文件,才能計算出多種內容,例如文件中有多少個元音等。出於測試目的,我剛剛將結果打印到控制台,但是我需要將其打印到單獨的文件中,所以我正在使用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();

如果您能告訴我為什么它不能打印到指定的輸出文件,那將非常感謝:)抱歉,這是一個相當長的問題。

您的PrintWriter已禁用自動刷新功能。 可以在構造函數中啟用它,也可以在關閉編寫器之前手動刷新它。 並且由於您讀取了行,因此應使用in.hasNextLine()而不是in.hasNext()

為了使程序正常工作,您需要先關閉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();

刷新時,內容將寫入文件。

最好的祝福。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM