1 / 30

Input/Output

Input/Output. Basic Classes. Contents. What is Stream? Reading Text Files Writing Text Files Handling I/O Exceptions. What Is Stream?. Streams Basics. What is Stream?. Stream is the natural way to transfer data in computer world

tassos
Télécharger la présentation

Input/Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Input/Output Basic Classes

  2. Contents • What is Stream? • Reading Text Files • Writing Text Files • Handling I/O Exceptions

  3. What Is Stream? Streams Basics

  4. What is Stream? • Stream is the natural way to transfer data in computer world • To read or write a file, we open a stream connected to the file and access the data via the stream Input stream Output stream

  5. Stream Basics • Streams are used for reading and writing data into and from devices • Streams are arranged series of bytes • Streams provide consecutive access to it’s elements • There are different streams for different types of need (working with files, strings, network and other) • Stream are opened before using them and closed after that

  6. Reading Text Files Using theScanner Class

  7. The ScannerClass • java.util.Scanner • Not a stream, but can works over streams • The easiest way to read a text file • Implements methods for reading strings and primitive types • Can be constructed by File object • Can specify the text encoding (for Cyrillic use windows-1251)

  8. Using Scanner for reading a Text File • Crating Scanner using File object: • The Scanner instances should always be closed : • Calling the close() method • Otherwise system resources can be lost File file = new File("test.txt"); Scanner fileInput = new Scanner(file, "windows-1251"); //Read file here... fileInput.close(); Specifies the text encoding.

  9. Reading a Text File Line by Line • Read and display a text file line by line File file = new File("somefile.txt"); //Next line may throw exception! Scanner fileInput = new Scanner(file); int lineNumber = 0; while (fileInput.hasNextLine()) { lineNumber++; System.out.printf("Line %d: %s%n", lineNumber, fileInput.nextLine()); } fileInput.close();

  10. Reading Text Files Live Demo

  11. Writing Text Files Using the PrintStream Class

  12. The PrintStreamClass • java.io.PrintStream • System.out is an instance of the java.io.PrintStream class. • Constructed by file name or other stream • Can define encoding (for Cyrillic use "windows-1251") PrintStream fileOutput = new PrintStream ( "test.txt", "windows-1251");

  13. Writing to a Text File • Create text file named "numbers.txt" with the numbers from 1 to 20 (one per line) //Next line may throw exception PrintStream fileOutput = new PrintStream("numbers.txt"); for (int number = 1; number <= 20; number++) { fileOutput.println(number); } fileOutput.close();

  14. Writing Text Files Live Demo

  15. Handling I/O Exceptions Introduction

  16. What is Exception? • "An event that occurs during the execution of the program that disrupts the normal flow of instructions“ – Google • Occurs when an operation can not be finished • Exception is thrown from some code • When exception is thrown, all operations after it are not processed • Exceptions tell that something unusual has happened, e. g. error or unexpected event

  17. How to Handle and Catch Exceptions? • Using try{} catch{} finally{} blocks in Java • Catch block specifies the type of exceptions that is caught try { // Some exception is thrown} catch (<exception type> ex) { // Exception is handled } finally { // Type functionality that must be performed // no matter if exception has occurred or not } try {...} catch (FileNotFoundException fnfe) { System.out.println("Can not find file."); }

  18. Handling Exceptions When Opening a File String fileName = "somefile.txt"; Scanner fileInput = null; try { fileInput = new Scanner(new File(fileName)); System.out.printf( "File %f successfully opened.%n", fileName); } catch (NullPointerException npe) { System.err.printf( "Can not find file %s.", fileName); } catch (FileNotFoundException fnf) { System.err.printf( "Can not find file %s.", fileName); }

  19. Handling I/O Exceptions Live Demo

  20. Reading and Writing Text Files More Examples

  21. Reading and WritingText Files – Example • Counting the number of occurrences of the word "foundme" a text file: Scanner fileInput =new Scanner( new File("somefile.txt)); int count = 0; while (fileInput.hasNext()){ String line = fileInput.nextLine(); int index = line.indexOf("foundme", 0) + 1; while (index != 0) { count++; index = line.indexOf("foundme", index) + 1; } } System.out.println(count); What is missing in this code?

  22. Fixing Subtitles – Example • Read subtitle file and fix it’s timing: Scanner fileInput = null; PrintStream fileOutput = null; try { // Create scanner with the Cyrillic encoding fileInput = new Scanner(new File("source.sub"), "windows-1251"); // Create PrintWriter with the Cyrillic encoding fileOutput = new PrintStream( "fixed.sub", "windows-1251"); String line; while (fileInput.hasNextLine()) { line = fileInput.nextLine(); fileOutput.println(fixLine(line)); } // Example continues…

  23. Fixing Subtitles – Example(2) } catch (FileNotFoundException fnfe) { System.out.println(fnfe.getMessage()); } catch (UnsupportedEncodingException uee) { System.out.println(uee.getMessage()); } finally { //remember to close the streams if (null != fileInput) { fileInput.close(); } if (null != fileOutput) { fileOutput.close(); } }

  24. Fixing Movie Subtitles Live Demo

  25. Summary • Streams are the main I/O mechanisms in Java • Reading text files is done by the Scanner class • Writing text files is done by the PrintStream class • Exceptions are unusual or error conditions • Can be handled by try-catch blocks

  26. Exercises • Write a program that reads a text file and prints only its odd lines on the console. • Write a program that reads a text file and inserts line numbers in front of each line. The result should be another text file. • Write a program that reads a text file containing a list of strings, sorts them and saves them to another text file. Example: Ivan George Peter Ivan Maria Maria George Peter

  27. Exercises (2) • Write a program that reads a text file containing a square matrix of numbers and finds in the matrix an area of size 2 x 2 with a maximal sum of its elements. The first line in the input file contains the size of matrix N. The next N lines contain N numbers separated by space. The output should be a in a separate text file – a single number. Example: 4 2 3 3 4 0 2 3 4 17 3 7 1 2 4 3 3 2

  28. Exercises (3) • Write a program that replaces all occurrences of the substring "start" with the substring "finish" in a text file. • Modify the solution of the previous problem to replace only whole words. • Write a program that extracts from given XML file all the text without the tags. Example: <?xml version="1.0"><student><name>Pesho</name> <age>21</age><interests count="3"><interest> games</instrest><interest>C#</instrest><interest> Java</instrest></interests></student>

  29. Exercises (4) • Write a program that deletes from given text file all odd lines. The result should be written to the same file. • Write a program that concatenates two text files in another file. • Write a program that deletes from a text file all words that start with the prefix "test". Words contain only the symbols 0...9, a...z, A…Z, _. • Write a program that compares two text files line by line and prints the number of lines that are different.

  30. Exercises (5) • Write a program that removes from a text file all words that are contained by given another text file. Handle all possible exceptions in your methods. • Write a program that reads a list of words from a file words.txt and finds how many times each of the words is contained in another file test.txt. The result should be written in the file result.txt and the words should be sorted by the number of their occurrences in descending order. Handle all possible exceptions in your methods.

More Related