170 likes | 354 Views
CSSE221 Section 2. JAVA File I/O. Overview. Using JFileChooser to ease use of file I/O in GUI programs Review of text-based file I/O Streams/Readers/Writers Using the File class to manage file systems Object-based, compressed, and byte-based file I/O. JfileChooser.
E N D
CSSE221 Section 2 JAVA File I/O
Overview • Using JFileChooser to ease use of file I/O in GUI programs • Review of text-based file I/O • Streams/Readers/Writers • Using the File class to manage file systems • Object-based, compressed, and byte-based file I/O
JfileChooser • When coding a GUI, JAVA provides a JFileChooser in swing. JFileChooser is very customizable, with features such as filters for file extensions when opening and saving. • Another advantage to JFileChooser is the ability to have it filter the list of files to only a few. If you wanted to pass only .txt files into a program, you would use a FileFilter or FilenameFilter with the JFileChooser.
JFileChooser – Markov Example publicstaticvoid main(String[] args) { JFileChooserjfc = newJFileChooser(); intreturnVal = jfc.showOpenDialog(jfc); //Here to make sure a valid file is selected if (returnVal == JFileChooser.APPROVE_OPTION) { String inputFile = jfc.getSelectedFile().toString(); int n = 1; // prefix-length intmaxWordsGen = 100; intmaxCharsPerLine = 20; Markov m = new Markov(inputFile, n, maxWordsGen, maxCharsPerLine); } else{ System.out.println("Failed because no file was selected"); } } • Markov will not work outright with this, as a few changes will need to be made to how Markov interprets file location, but the correct file will be selected.
JFileChooser – FileFilter • The FileFilter Interface requires the method: public boolean accept(File f) • To use a FileFilter with the JFileChooser from the last example, the following code would be placed after JFileChooserjfc was initialized: jfc.addChoosableFileFilter(new FileFilter(){…}); jfc.setAcceptAllFileFilterUsed(false);
Text-Based File I/O Review Basic text-based file I/O review: File name=new File(“file.txt”); BufferedReaderfileIn=null; try{ fileIn=new BufferedReader(new FileReader(name)); //read your data in }catch(IOException e){ //error handling }finally{ fileIn.close(); }
I/O Streams • Streams are the basis of all I/O in Java (terminal, web sockets, files, etc…). • A Stream is created for EITHER input or output, NOT both • The Reader and Writer classes we commonly use are extension of the Stream classes • The Scanner used with Markov is an example of a “simplified” input class, though it does not directly extend a Stream • The Stream concept is important, and we will revisit it later when discussing other types of I/O
Buffered Classes • Buffered Classes: a Buffered class extends its lower counterpart (i.e. BufferedReader extends FileReader). • Buffering allows reading of more than a single “piece” of data at a time. • Whether or not you want to use Buffered classes is largely a design/functionality decision
Implementation Rules • Correct order of instantiation must be followed • A Stream/Reader/Writer must be initialized inside a try/catch/finally block that catches an IOException. • The “outermost” Stream/Reader/Writer needs to be declared and set to null BEFORE the try/catch block • A Stream/Reader/Writer needs to be closed (preferably in the finally block), or else: • Files written will not “finalize” and will not appear correctly. Files read may be “locked” into the program, and not be available elsewhere. • Only a limited number of Streams can be open at once.
File • The File class creates an object representing a file on the user’s system • Constructors: • new File(String name); • new File(File parent, String suffix); • new File(File parent, File suffix); • Useful methods: • exists() • createNewFile() • isDirectory() • length()* • lastModified()* • list() • listFiles()
Demo • Review of text-based file I/O • Using the File class to define and organize files • Using the File class to gather data about and modify files
Activity ! ! This exercise builds off the file structure already created in the fileSystemExample() and textIOExample() so keep in mind the location and state of the files after that code is run • Take the text from textFile.txt, and append it to the end of data/existingData.txt • Next, move the textFile.txt file to the data/newData directory as newFile.dat (HINT: the older textFile.txt may be removed in the process) • BONUS: within data/newData, create a directory named for each line of data/existingData.txt
Object-Based I/O • Saving/retrieving data for use in a program can become complicated, using Object I/O can save you from having to convert/organize all your data for text-based I/O • Uses ObjectOuputStream and ObjectInputStream classes • Objects may be written to a file as long as they implement the Serializable interface. • See example code in full version of Demo
Compressed File I/O • Compressed I/O allows you to write data to.zip files which can save space and make archiving easier. • Uses GZIPOutputStream and GZIPInputStream, and is implemented after the basic/buffered level, but before the specific level. • See example code in full version of Demo
Byte-Based I/O • Byte-based I/O allows Java to handle reading/writing of files that are neither text-based nor object based. • Uses DataInputStream and DataOutputStream • NOTE: unlike text-based and object-based, information read into the program can only be worked with if the decoding is known. • Again, see example code in full version of Demo
Code Quick Reference • BufferedInputStream • read(); • close(); • BufferedReader • read(); • readLine(); • close(); • ObjectInputStream • readObject(); • close(); • DataInputStream • readFully(byte[] b); • BufferedOutputStream • write(); • BufferedWriter • write(); • newLine(); • close(); • ObjectOutputStream • writeObject(); • close(); • DataOutputStream • write();