40 likes | 60 Views
Understand text and binary files, import statements, file handling in Java, reading and writing data using PrintWriter and Scanner, managing exceptions.
E N D
File IO • a collection of data • can be written and read sequentially • has a name • typically supported by OS • allows for permanent / persistent storage • two main types of files • text file • binary file • text files • data accessed as characters • Java source files (*.java) are text files • a *.txt file is text file • binary files • data accessed in bytes • usually interpreted by another program • compiled class files (*.class) are binary files • pictures (*.jpg or *.gif) are binary files
File Output • Need import statements at top of program • import java.io.PrintWriter;import java.io.FileNotFoundException; • PrintWriter constructor needs a String • The name of the file • in current directory • String fileName = "myFile.txt"; • or full path name • String fileName = "C:\\ics111\\docs\\myFile.txt"; • the delimiter '\\' is a backslash • better: use slash '/'; it's platform-independent: • String fileName = "C:/ics111/docs/myFile.txt"; • new PrintWriter() constructor • if the file does not exist either creates it, • or overwrites an existing file • must be in a try-catch block for exception if file can't be found • try { PrintWriter writer = new PrintWriter(fileName); // write to writer using print()} catch(FileNotFoundException error){ System.out.println(error); System.exit(1); // ends program}
File Input • Need import statements at top of program • import java.io.Scanner;import java.io.File;import java.io.FileNotFoundException; • File constructor needs a String • The name of the file • in current directory • String fileName = "myFile.txt"; • or full path name • String fileName = "C:/ics111/docs/myFile.txt"; • new Scanner() constructor • doesn't creates the file • or only connects to a file • we can ask whether the file exists • must be in a try-catch block for exception if file can't be found • try { File file = new File (fileName); Scanner scanner = new Scanner(file); // read from scanner } catch (FileNotFoundException error) { System.out.println(error); System.exit(1); //ends program}
Reading File • reading a file correctly isn't simple • try { InputStream input = new FileInputStream(file); try { LineNumberReader reader = new LineNumberReader (new InputStreamReader(input)); String text = ""; String line = reader.readLine(); for (; line != null; line = reader.readLine()) { text += line + "\n"; } // now text contains the contents of the file } catch (IOException error) { //handle reading error } finally { try {input.close (); } catch (IOException error) { //handle closing error } }} catch (FileNotFoundException error) { //handle non-existing file error}