Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Unit 6 Working with files. Unit 6 Working with files."— Presentation transcript:

1

2 Unit 6 Working with files

3 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

4 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

5 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"));

6 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

7 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(" ");

8 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();

9 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

10 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

11 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!"); }

12 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

13 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

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

15 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)); } }

16 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

17 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"));

18 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!"); }

19 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

20 Extension

21 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

22 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(); }

23 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

24 End of Unit


Download ppt "Unit 6 Working with files. Unit 6 Working with files."

Similar presentations


Ads by Google