mirror of
https://gitlab.com/magicalsoup/Highschool.git
synced 2025-01-24 00:21:45 -05:00
1.4 KiB
1.4 KiB
Reading and Outputting Files
Outputing To Files - you can save it for future use - The printwriter class can be used to createa file and wrtie data to it - necessay imports:
import java.io.IOException;
import java.io.PrintWriter;
- Or:
import java.io.*;
- It is declared similarly to the scanner class
Different types of file can be created for data to be written to, depends on the extension eg. “.txt” creates a text file while docsx creates a docx document
code
Reading To Files
- Speed
- Less errors
- Easier to read individual cases
- able to get data from sources other than keyboard
- changing information is easy only to file
- more efficient less time to test
- large amounts of data can be entered quickly
- at the testing stage, data can be easily
How
- The file class is java’s representation of a file or directoy path
- it is used to identify/ocate the file that is to be read
- code
- Scanner calss is used to read from file
Sample Code
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class ReadingToFileDemo {
public static void (String[]args) throws IOException {
File file = new File("test.txt); // the file you are reading from
Scanner read = new Scanner(file);
while(read.hasNext()) {
System.out.println(read.nextLine());
.next();
read}
}
}