BufferReader to write new file with previous info

2019-09-19 20:28发布

问题:

This is the basis of my code. It prints students grades on the console, but how do I use a Buffereader to put all the students grade on a new file.

import java.io.*;
import java.util.InputMismatchException;
import java.lang.*;
import java.util.*;

public class WorkSpace {

private Scanner x;

    public void openFile(){
        try{
            x = new Scanner (new File ("grades.txt"));
        }
        catch(Exception e){
            System.out.println("could not find file");
        }}



    public void createFile()throws IOException {


        try{
            File file = new File("grades.txt");
            Scanner s = new Scanner(file);




        while(s.hasNext()){
        {
            String [] split = s.nextLine().split(", ");

            String fname = split[0];

            Double q1 = Double.parseDouble (split[1]);
            Double q2 = Double.parseDouble (split[2]);
            Double q3 = Double.parseDouble (split[3]);
            Double q4 = Double.parseDouble (split[4]);
            Double proji = Double.parseDouble (split[5]);
            Double projii = Double.parseDouble (split[6]);
            Double projiii = Double.parseDouble (split[7]);

            double studentgrade = (q1 *0.1) + (q2 *0.1) +(q3 *0.1) + (q4 *0.1) +(proji*0.15) + (projii * 0.2) + (projiii *0.25);
            if(studentgrade>90)
                System.out.printf("%s got an A\n", fname);
            else if(studentgrade>80)
                System.out.printf("%s got a B\n", fname);
            else if(studentgrade>70)
                System.out.printf("%s got a C\n", fname);
            else if(studentgrade>60)
                System.out.printf("%s got a D\n", fname);
            else if(studentgrade>50)
                System.out.printf("%s got a F\n", fname);


        }}}catch(Exception e){
            e.printStackTrace();
        }



    }
    public void closeFile(){
        x.close();
    }

回答1:

Scanner.nextInt() returns next integer value read from source (not source length or something). You open the file and try to read integer in the beginning, but the file doesn't start with integer so you get an exception.



回答2:

How you are reading your file is incorrect. The most common way to read files with scanner:

try{
File file = new File("Your/File/Path");
Scanner s = new Scanner(file);
s.useDelimiter("\n");//splits the whole file's text by "\n"
while(s.hasNext()){
String next = s.next();
//parse your stuff
}
s.close();
}catch(Exception e){}

Also, scanner.nextInt() doesn't return the file's length. That was the problem. Use file.length to get the file's length.



回答3:

Your question doesn't make sense. BufferedReader doesn't write files. It, err, reads files. What you want is, err, a BufferedWriter.