viewBox="0 0 51 48">Five Pointed Star Five Pointed Star

Reading and writing Strings to files (Java)

input file con­tains: A=Excellent B=Good C=Adequate D=Marginal E=Unacceptable

 import java.io.*; 
import java.util.Scanner; 
/** * Write a description of class Driver here. 
* * @author Larry Ball 
* @version Fri Oct 14 23:32:52 CDT 2011 */ 
public class Driver { public Driver() { 
   // nothing to do here 
   } 
public static void main(String[] args) { 
    String line; 
    String grade = "Grade "; 
    String is = " is "; 
    BufferedReader in; 
    PrintWriter out; 
    try { 
        in = new BufferedReader(new FileReader("input.txt")); 
        line = in.readLine();     
        in.close(); 
        String[] frags = line.split("[= ]+"); 
        StringBuilder sb = new StringBuilder(); 
        for (int i = 0; i < frags.length; i += 2) {     
            sb.append(grade); 
            sb.append(frags[i]); 
            sb.append(is); 
            sb.append(frags[i+1]); 
            sb.append("\n"); 
        } 
        String newLine = sb.toString(); 
        File f = new File("output.txt"); 
        out = new PrintWriter(new FileWriter(f));
        out.println(newLine); out.close(); 
        } catch (FileNotFoundException fnfe) {
            System.err.println("File not found."); 
            fnfe.printStackTrace(); 
            System.exit(1); 
        } catch (IOException ie) { 
        System.err.println("IO Exception occurred"); 
        ie.printStackTrace(); System.exit(2); } } }

Out­put file con­tains:
Grade A is Excel­lent
Grade B is Good
Grade C is Ade­quate
Grade D is Mar­ginal
Grade E is Unacceptable


L. Ball
L. Ball

Father. Developer. Coffee Connoisseur. Amateur Guitarist.