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 ne
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 i.e: "," 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!
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);
}
}
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.
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();