简体   繁体   中英

Reading and Writing to a .txt file in Java

Here is my prompt for the assignment: Your program needs to read the information from a text file instead of using a scanner to read from command line. Your program also needs to write the messages into a text file instead of showing the messages on the screen.

I have the code written and running for it to prompt using the CLI. However, I have absolutely no idea how to change the code utilizing a text file. Can someone please explain this to me?

Code so far:

import java.util.*;

public class parallelArrays {

    public static void main(String[] args) {
       String[] names;
       int[] exam1Grades;
       int[] exam2Grades;
       int n, sum1, sum2;
       double avg1,avg2;

       Scanner kb = new Scanner(System.in);

       // Get the number of students from the user
       System.out.print("Enter # of students:");
       n = kb.nextInt();

       // Allocate the arrays
       names = new String[n];
       exam1Grades = new int[n];
       exam2Grades = new int[n];

       // Input the names and grades
       for (int i=0; i<=names.length-1; i++) {
          System.out.print("Enter name for student #" + (i+1) + ":");
          names[i] = kb.next();
          System.out.print("Enter exam #1 grade:");
          exam1Grades[i] = kb.nextInt();
          System.out.print("Enter exam #2 grade:");
          exam2Grades[i] = kb.nextInt();
       }

       // Add up all the grades (could have been done in the above loop)
       sum1 = 0;
       sum2 = 0;
       for (int i=0; i<=names.length-1; i++) {
          sum1 = sum1 + exam1Grades[i];
          sum2 = sum2 + exam2Grades[i];
       }

       // Calculate and output the averages
       avg1 = sum1/n;
       System.out.println();
       System.out.println("Exam #1 average: " + avg1);

       avg2 = sum2/n;
       System.out.println("Exam #2 average: " + avg2);
       System.out.println();

       // Compare each grade to the average
       for (int i=0; i<=names.length-1; i++) {
       if (exam1Grades[i] > avg1)
           System.out.println("Student " + names[i] + " is above average on exam 1");
           else if (exam1Grades[i] < avg1)
           System.out.println("Student " + names[i] + " is below average on exam 1");
           else
           System.out.println("Student " + names[i] + " is average on exam 1");

       if (exam2Grades[i] > avg2)
           System.out.println("Student " + names[i] + " is above average on exam 2");
           else if (exam2Grades[i] < avg2)
           System.out.println("Student " + names[i] + " is below average on exam 2");
           else
           System.out.println("Student " + names[i] + " is average on exam 2");

       }
    }
}

like @Shobit said previously, use a BufferedWriter in conjunction with a FileWriter and with the methods write() and newLine() you can insert the lines you want to the file in stead of using Println.

BufferedWriter writer = new BufferedWriter(new FileWriter("path-of-file")); //you don't need to create a File object, FileWriter takes a string for the filepath as well
writer.write("Student number..."); 
writer.writeLine(); //for a new line in the file

and when you are done writing to the file,

writer.close();

You can use the Scanner class the same way you use it to read the names of the file. All you have to do is define how you will structure your file. For example, separate your info with a special character ie: "," and use that as a token to identify the different fields in your file for the name, grades, etc. (see the Pattern and Scanner APIs to use REGEX's for this)

You might want to create a Student class and map the needed fields to that class, add them to a List and iterate over that much easier.

As for writing to a text file, you are already doing it, check FileWriter to see how to add a new line and that will be it. Good Luck!

You could use BufferedReader and BufferedWriter to read from/write to a file in Java. The BufferedReader constructor takes a FileReader object, whose constructor takes a File object. It looks something like this:

BufferedReader br = new BufferedReader(new FileReader(new File("path-of-file")));

You can then read line-by-line from the file using the BufferedReader's readLine() (or any of the other methods depending on your use case).

Analogically, there is also BufferedWriter and a FileWriter and a write() method for writing.

Closing the reader and writer streams after reading/writing is always a good habit. You can use the close method on the streams to do the same.

Hope that helps.

    import java.nio.file.path;
    import java.nio.file.paths;
    class FileCopy {
    public static void main(String args[])
    {
    Path sour =Paths.get("Source path");
    Path dest =Paths.get("destination path"); // The new file name should be given  

    or else FileAlreadyExistsException occurs.                                            

    Files.copy(sour, dest);
    }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM