1
0
mirror of https://gitlab.com/magicalsoup/Highschool.git synced 2025-01-23 16:11:46 -05:00
highschool/Grade 10/Computer Science/ICS4U1/Reading And Writing To Files.md
2019-09-20 15:44:18 +00:00

1.4 KiB
Raw Blame History

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 javas 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());
            read.next();
        }
    }
}