Unit 6 Working with files. Unit 6 Working with files.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Today Assignment 2 is posted. Due the first Friday after Reading Week. (“Virtual” lecture looked at the use of try/catch and try with resources blocks.
CS 206 Introduction to Computer Science II 09 / 14 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 09 / 04 / 2008 Instructor: Michael Eckmann.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
Handling errors Exception handling and throwing Simple file processing.
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Two Ways to Store Data in a File Text format Binary format.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
CS 206 Introduction to Computer Science II 09 / 11 / 2009 Instructor: Michael Eckmann.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Creating a GUI Class An example of class design using inheritance and interfaces.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
OO Design and Programming II I/O: Reading and Writing
File Input / Output.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
University of Central Florida COP 3330 Object Oriented Programming
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Week 14 - Wednesday CS 121.
I/O Basics.
Creating and Modifying Text part 2
Simple Java I/O part I Using scanner 8-Nov-18.
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
File class File myFile=new File(“c:/javaDemo/aa
Streams and File I/O Chapter 14.
Java for Teachers Intermediate
<INSERT_WITTY_QUOTE_HERE>
Fundamentals of Data Structures
Workshop for Programming And Systems Management Teachers
Exceptions handling Try, catch blocks Throwing exceptions.
Workshop for Programming And Systems Management Teachers
Lecture 11 Objectives Learn what an exception is.
Exceptions.
Exceptions 10-May-19.
Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Observer pattern, MVC, IO & Files
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

Unit 6 Working with files

Introduction This term we have mainly looked at sorting algorithms For this lesson, we will take a look at something different We will learn how Java can work with files

Introduction There are several ways to read and write to files in Java We are going to use two classes BufferedReader BufferedWriter Let’s start with reading numbers from a file

Reading numbers First of all, we will need to make a list of Integers: Next, we will need to create a BufferedReader It accepts a FileReader as a parameter FileReader’s constructor accepts the name of the file we would like to use: You will get an “unhandled exception” error, ignore it for now List<Integer> list = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

Create a new project – T02U06_Files Create a package – main Create a class – Program Create an ArrayList of integer numbers Create a BufferedReader Pass new FileReader("input.txt") as a parameter

Reading numbers Lets now read one line from the text file You can use reader.readLine() to do this: This will give us a single line with all numbers, including spaces between them We will need to split it into separate strings: String text = reader.readLine(); String [] numbers = text.split(" ");

Reading numbers All we have to do now is parse all numbers and add them to the list: Finally, we will need to close the reader: You will see even more errors, ignore them for now as well for(String s : numbers) { list.add(Integer.parseInt(s)); } reader.close();

Create a string variable and read a line to it Create an array of strings and call it numbers Split your text using a single space Add a for loop that goes over all elements in numbers It should parse them and add to the list Close the reader at the end

Exceptions At the moment, there are some errors in the code Some methods that we’ve used throw checked exceptions These are exceptions that must be handled in our code One can be thrown when we create a reader It’s called FileNotFoundException and we get it when the file does not exist The other one is IOException, which is an exception for all generic input/output errors Finally, we can also catch all other exceptions to handle cases when numbers in the file aren’t in the right format

Exceptions try { BufferedReader reader = new BufferedReader(new FileReader("input.txt")); String text = reader.readLine(); String [] numbers = text.split(" "); for(String s : numbers) { list.add(Integer.parseInt(s)); } reader.close(); } catch(FileNotFoundException e) { System.out.println("File not found!"); } catch (IOException e) { System.out.println("I/O exception!"); } catch (Exception e) { System.out.println("Something went wrong!"); }

Add a try block before the BufferedReader Add a catch block after reader.close for a FileNotFoundException Add a catch block for an IOException Add a catch block for all other Exceptions N/A N/A

Testing We need to do something with the list Let’s print it to the console after the try-catch block If something goes wrong, our program won’t crash and the list will be just empty Also, we need to make a new text file You will need to make it in the project folder (not src directory!) And then fill it with some numbers and separate them with spaces

Print your list to the console Create a new text file Fill it with some numbers Run your program N/A N/A

Multiple lines Let’s now change the program a little bit At the moment, it only works for one line of numbers Let’s make it work for multiple lines as well All we have to do is put reading lines inside a while loop: The condition inside the loop saves a line in text and checks that the result is not null – which would mean the end of the file String text; while((text = reader.readLine()) != null) { String[] numbers = text.split(" "); for (String s : numbers) { list.add(Integer.parseInt(s)); } }

Add a while loop before you make the numbers array It should use (text = reader.readLine()) != null for it’s condition Test your program with multiple lines of text N/A N/A N/A

Writing to Files Writing to files is very similar to reading We make a new BufferedWriter and then use writer.write() to write to the file However, before we do this, let’s use Collections.sort() to sort our numbers: Then, we can add a try-catch block and make a new buffered writer: Collections.sort(list); BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

Writing to Files Next, we use a for loop to write all numbers to the file: Then, we close the writer: And, finally, add a catch block: We don’t really have to catch any other exceptions If an output file is missing it will be created for us for(int i : list){ writer.write(i + " "); } writer.close(); }catch (IOException e){ System.out.println("Can't write to the file!"); }

Sort your list using Collections.sort() And a try-catch block that catches IO exceptions Inside try, make a new BufferedWriter Use a for loop to write all numbers to the file Close the writer Test your program

Extension

Create a static function called log It should accept one parameter – a string This function is supposed to print the string to the console … and write it to a text file as well Make sure it adds a timestamp Use “new Timestamp(System.currentTimeMillis()).toString()“ for it

Using Scanner There is another way to read data from files You can use the Scanner class, that we have previously used for user input Scanners are a little bit slower than BufferedReaders, but allow to read numbers directly try { Scanner s = new Scanner(new File("input.txt")); while (s.hasNextLine()) { int i = s.nextInt(); System.out.println(i); } s.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }

Create a function called findSum It should use a scanner to read numbers from a text file And return their sum Don’t forget to add a try-catch block And to close your Scanner as well N/A

End of Unit