输出到封闭流?

时间:2013-11-05 04:12:03

标签: java

所以我修复了我的程序,但问题是用tildes替换所有空格后我必须将文本输出到已关闭的文件。我如何重新打开文件输出并输入内容?

//Name: Allen Li
//Program file: Vowels.Java 
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)


import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class

public class Vowels { //class
 public static void main(String[] args) { //main method

  try { //try block
   FileReader poetry = new FileReader("poetry.txt"); 
   FileWriter dentist = new FileWriter( 
     "LI_ALLEN_dentist.txt"); 

   int a; 
   while ((a = poetry.read()) != -1) { 
    dentist.write(a); 
    System.out.print((char) a); //print the file to the monitor
   } 

   poetry.close(); 
   dentist.close(); 

   Scanner inFile = new Scanner(new File( 
     "LI_ALLEN_dentist.txt")); 

   int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
   int numOfVowelsE = 0; 
   int numOfVowelsI = 0; 
   int numOfVowelsO = 0; 
   int numOfVowelsU = 0; 

   while (inFile.hasNext()) { 
    String sentence = inFile.next() /* ("\\S+") */; 

    for (int i = 0; i <= sentence.length() - 1; i++) { 
     if (sentence.toLowerCase().charAt(i) == 'a') { 
      numOfVowelsA++; 
     } 
     if (sentence.toLowerCase().charAt(i) == 'e') { 
      numOfVowelsE++; 
     } 
     if (sentence.toLowerCase().charAt(i) == 'i') { 
      numOfVowelsI++; 
     } 
     if (sentence.toLowerCase().charAt(i) == 'o') { 
      numOfVowelsO++; 
     } 
     if (sentence.toLowerCase().charAt(i) == 'u') { 
      numOfVowelsU++; 
     } 
    } 
   } 
   System.out.println(); 

   System.out.println("There are " + numOfVowelsA 
     + " A vowels in this file of text"); 
   System.out.println("There are " + numOfVowelsE 
     + " E vowels in this file of text."); 
   System.out.println("There are " + numOfVowelsI 
     + " I vowels in this file of text."); 
   System.out.println("There are " + numOfVowelsO 
     + " O vowels in this file of text."); 
   System.out.println("There are " + numOfVowelsU 
     + " U vowels in this file of text. "); 



   Scanner tildes = new Scanner(new File( 
     "LI_ALLEN_dentist.txt")); 
   while (tildes.hasNext()) { 
    String replace = tildes.nextLine(); 
    replace = replace.replaceAll(" ", "~"); 
    System.out.println(); 
    System.out.print(replace); 

   } 

  } catch (FileNotFoundException i) { 
   System.out.println("The file you are trying to use as input is not found. " + i); 
  } catch (IOException i) { 
   System.out.println("There is an issue with the input or output file. " + i); 
  } 
 } 
}

1 个答案:

答案 0 :(得分:0)

您没有关闭inFile。首先关闭inFile,然后您可以在tildes中重新打开它。 在Scanner tildes = new Scanner(...);行之前关闭它。