Download presentation
Presentation is loading. Please wait.
Published byWilfrid Hines Modified over 9 years ago
1
Lab1: File I/O and Streams Lecturer: Mauro Conti T.A.: Eyüp S. Canlar
2
Exercise 1 Write a program that Gets the filename from the command line e.g. java Ex1 Reads the binary file with given name Handles any exceptions like FileNotFoundException and IOException In the case of an exception the program exits with status -1, otherwise (success) with status 0. You have 30 minutes.
3
Exercise 1: open, read, close File file = new File(filename); try{ FileInputStream fin = new FileInputStream(file); while(true){ // read file } fin.close(); } catch(Exception e){ …. }
4
Exercise 1: catch exceptions try{ //open, read, and close file } catch(NoSuchFileException nsfe){ … return -1; } Catch(IOException ioe){ …. return -1; }
5
Exercise 2 Write a java program that Reads values from the text file values.txt Computes for each one of the two value types the average values.txt contains on each line [VALUE_TYPE]=[VALUE] With VALUE_TYPE :={I1, I2} VALUE :={1, 2, …} You have 30 minutes.
6
Exercise 2: open, read, close try{ FileReader fr = new FileReader(“values.txt”); BufferedReader br = new BufferedReader(fr); while(//some condition){ //read file line by line //parse each line } fr.close(); } catch(Exception e){}
7
Exercise 2: parse file try{ //open file while(//some condition){ String s = //read 1 line of values.txt StringTokenizer st = new StringTokenizer(s, “=“); st.nextToken(); if(st.equals(“I1”)){ i1Counter += new Integer(st.nextToken()).intValue(); …. } //close file }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.