120 likes | 307 Views
https://xliu12.mysite.syr.edu/. Java Files (File I/O). IST 256 Application Programming for Information Systems Xiaozhong Liu Yatish Hegde. File I/O. Read. Memory (Primary Memory). Hard Disk (Secondary Memory). Process. Write. Input Stream. Output Stream.
E N D
https://xliu12.mysite.syr.edu/ Java Files (File I/O) IST 256 Application Programming for Information Systems Xiaozhong Liu YatishHegde
File I/O Read Memory (Primary Memory) Hard Disk (Secondary Memory) Process Write
Input Stream Output Stream I/O Streams Default input/output streams
Java - Streams JAVA provides 2 types of streams Text streams-containing ‘characters‘ Program Device I ‘ M A S T R I N G \n Binary Streams - containing 8 – bit information Program Device 01101001 11101101 00000000
Reading and Writing Files • Create a stream object and associate it with a disk-file • Give the stream object the desired functionality • while there is more information read(write) next data from(to) the stream • close the stream
Reading Files import java.io.*; public static void readFile() { BufferedReader ins = new BufferedReader(new FileReader(“test.txt”)); while(ins.ready()) { String s = ins.readLine(); System.out.println(s); } ins.close(); } Important: Place the code inside Try{…} Catch{….} Wherever necessary
Writing File import java.io.*; public static void writeFile() { String s = “I love programming”; BufferedWriter outs = new BufferedWriter(new FileWriter(“test_out.txt”)); outs.write(s); } outs.close(); Important: Place the code inside Try{…} Catch{….} Wherever necessary
Reading tokens from file import java.io.*; Import java.util.Scanner; Public static void readFile() { BufferedReader ins = new BufferedReader(new FileReader(“test.txt”)); Scanner scanner = new Scanner(ins); while(scanner.hasNext()) { System.out.println(scanner.next()); } scanner.close(); } Important: Place the code inside Try{…} Catch{….} Wherever necessary
Browse Files using GUI private void jButton1ActionPerformed(java.awt.event.ActionEventevt) { JFileChooserfc = new JFileChooser(); if(fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String inputFilePath= file.getAbsolutePath().toString(); jTextField1.setText(inputFilePath); } }
Try this for fun • In a notepad, type few sentences and save the file as test.txt. Write a Java program to read the text in test.txt and write that to file test_out.txt. • In a notepad, type 10 numbers (any numbers in the range 0 to 10) separated by white space and save the file as grade.txt. Write a Java program to read the numbers from grade.txt, calculate the average grade and print the output. • In a notepad, type fivenames (one name per line) and save the file as name.txt. Create a GUI from which you can select (browse button) the file name.txt and write (create button) the names in name.txt to file name_out.txt (one name per line).