Basic input-output-v.1.1

30
Basic Classes Basic Classes Input/Output Input/Output

description

Working with text files in Java

Transcript of Basic input-output-v.1.1

Page 1: Basic input-output-v.1.1

Basic ClassesBasic Classes

Input/OutputInput/Output

Page 2: Basic input-output-v.1.1

ContentsContents

• What is Stream?What is Stream?

• Reading Text FilesReading Text Files

• Writing Text FilesWriting Text Files

• Handling I/O ExceptionsHandling I/O Exceptions

Page 3: Basic input-output-v.1.1

What Is Stream?What Is Stream?Streams BasicsStreams Basics

Page 4: Basic input-output-v.1.1

What is Stream?What is Stream?

• Stream is the natural way to transfer data in Stream is the natural way to transfer data in computer worldcomputer world

• To read or write a file, we open a stream To read or write a file, we open a stream connected to the file and access the data via connected to the file and access the data via the streamthe stream

Input stream

Output stream

Page 5: Basic input-output-v.1.1

Stream BasicsStream Basics

• Streams are used for reading and writing Streams are used for reading and writing data into and from devicesdata into and from devices

• Streams are arranged series of bytesStreams are arranged series of bytes

• Streams provide consecutive access to it’s Streams provide consecutive access to it’s elementselements

• There are different streams for different types There are different streams for different types of need (working with files, strings, network of need (working with files, strings, network and other)and other)

• Stream are opened before using them and Stream are opened before using them and closed after thatclosed after that

Page 6: Basic input-output-v.1.1

Reading Text FilesReading Text FilesUsing theUsing the ScannerScanner Class Class

Page 7: Basic input-output-v.1.1

The The ScannerScanner ClassClass

• java.util.Scannerjava.util.Scanner

• Not a stream, but can works over streams Not a stream, but can works over streams

• The easiest way to read a text fileThe easiest way to read a text file

• Implements methods for reading strings and Implements methods for reading strings and primitive typesprimitive types

• Can be constructed by Can be constructed by FileFile object object

• Can specify the text encoding (for Cyrillic use Can specify the text encoding (for Cyrillic use windows-1251windows-1251))

Page 8: Basic input-output-v.1.1

Using Using ScannerScanner for reading a for reading a Text FileText File

• Crating Crating ScannerScanner using using File File object:object:

• The The ScannerScanner instances should always be instances should always be closed :closed :• Calling the Calling the cclose()lose() method method

• Otherwise system resources can be lostOtherwise system resources can be lost

File file = new File("test.txt");File file = new File("test.txt");Scanner fileInput = new Scanner(file,Scanner fileInput = new Scanner(file,

"windows-1251");"windows-1251");//Read file here...//Read file here...fileInput.close();fileInput.close(); Specifies the Specifies the

text encoding.text encoding.Specifies the Specifies the

text encoding.text encoding.

Page 9: Basic input-output-v.1.1

Reading a Text File Line by Reading a Text File Line by LineLine

• Read and display a text file line by lineRead and display a text file line by line

File file = new File("somefile.txt");File file = new File("somefile.txt");

//Next line may throw exception!//Next line may throw exception!Scanner fileInput = new Scanner(file); Scanner fileInput = new Scanner(file);

int lineNumber = 0;int lineNumber = 0;

while (fileInput.hasNextLine()) {while (fileInput.hasNextLine()) { lineNumber++;lineNumber++; System.out.printf("Line %d: %s%n",System.out.printf("Line %d: %s%n",

lineNumber, fileInput.nextLine());lineNumber, fileInput.nextLine());}}

fileInput.close();fileInput.close();

Page 10: Basic input-output-v.1.1

Reading Text FilesReading Text FilesLive DemoLive Demo

Page 11: Basic input-output-v.1.1

Writing Text FilesWriting Text FilesUsing the Using the PrintStreamPrintStream Class Class

Page 12: Basic input-output-v.1.1

The The PrintStreamPrintStream ClassClass

• java.io.PrintStreamjava.io.PrintStream

• System.outSystem.out is an instance of the is an instance of the java.io.PrintStreamjava.io.PrintStream class. class.

• Constructed by file name or other streamConstructed by file name or other stream

• Can define encoding (for Cyrillic use Can define encoding (for Cyrillic use "windows-1251")"windows-1251")

PrintStream fileOutput = new PrintStream (PrintStream fileOutput = new PrintStream ( "test.txt", "windows-1251");"test.txt", "windows-1251");

Page 13: Basic input-output-v.1.1

Writing to a Text FileWriting to a Text File

• Create text file named "Create text file named "numbers.txtnumbers.txt" with the " with the numbers from 1 to 20 (one per line)numbers from 1 to 20 (one per line)

//Next line may throw exception//Next line may throw exceptionPrintStream fileOutput =PrintStream fileOutput =

new PrintStream("numbers.txt");new PrintStream("numbers.txt");

for (int number = 1; number <= 20; number++) {for (int number = 1; number <= 20; number++) {fileOutput.println(number);fileOutput.println(number);

}}

fileOutput.close();fileOutput.close();

Page 14: Basic input-output-v.1.1

Writing Text FilesWriting Text FilesLive DemoLive Demo

Page 15: Basic input-output-v.1.1

Handling I/O ExceptionsHandling I/O ExceptionsIntroductionIntroduction

Page 16: Basic input-output-v.1.1

What is Exception?What is Exception?

• "An event that occurs during the execution "An event that occurs during the execution of the program that disrupts the normal flow of the program that disrupts the normal flow of instructions“ – Googleof instructions“ – Google

• Occurs when an operation can not be Occurs when an operation can not be finishedfinished

• Exception is thrown from some codeException is thrown from some code

• When exception is thrown, all operations after When exception is thrown, all operations after it are not processedit are not processed

• Exceptions tell that something unusual has Exceptions tell that something unusual has happened, e. g. error or unexpected eventhappened, e. g. error or unexpected event

Page 17: Basic input-output-v.1.1

How to Handle and Catch How to Handle and Catch Exceptions?Exceptions?

• Using Using trytry{}{} catch catch{} {} finallyfinally{} blocks in Java{} blocks in Java

• Catch block specifies the type of exceptions Catch block specifies the type of exceptions that is caughtthat is caught

try {try { // Some exception is thrown// Some exception is thrown} catch (<exception type> ex) {} catch (<exception type> ex) { // Exception is handled // Exception is handled} finally {} finally { // Type functionality that must be performed // Type functionality that must be performed // no matter if exception has occurred or not // no matter if exception has occurred or not }}

try {...} catch (FileNotFoundException fnfe) {try {...} catch (FileNotFoundException fnfe) { System.out.println("Can not find file.");System.out.println("Can not find file.");}}

Page 18: Basic input-output-v.1.1

Handling Exceptions When Handling Exceptions When Opening a FileOpening a File

String fileName = "somefile.txt";String fileName = "somefile.txt";Scanner fileInput = null;Scanner fileInput = null;try {try { fileInput = new Scanner(new File(fileName));fileInput = new Scanner(new File(fileName)); System.out.printf(System.out.printf(

"File %f successfully opened.%n", fileName);"File %f successfully opened.%n", fileName);} catch (NullPointerException npe) {} catch (NullPointerException npe) { System.err.printf(System.err.printf(

"Can not find file %s.", fileName);"Can not find file %s.", fileName);

} catch (FileNotFoundException fnf) {} catch (FileNotFoundException fnf) { System.err.printf(System.err.printf(

"Can not find file %s.", fileName);"Can not find file %s.", fileName);}}

Page 19: Basic input-output-v.1.1

Handling I/O ExceptionsHandling I/O ExceptionsLive DemoLive Demo

Page 20: Basic input-output-v.1.1

Reading and Writing Text Reading and Writing Text FilesFiles

More ExamplesMore Examples

Page 21: Basic input-output-v.1.1

Reading and WritingReading and WritingText Files – ExampleText Files – Example

• Counting the number of occurrences of the Counting the number of occurrences of the word "word "foundmefoundme" a text file:" a text file:

Scanner fileInput =Scanner fileInput = new Scanner(new Scanner(new File(new File(""somefilesomefile.txt).txt)));;

int count = 0;int count = 0;while (fileInput.hasNext()){while (fileInput.hasNext()){

String line = fileInput.String line = fileInput.nextnextLine();Line(); int index = line.indexOf("foundme", 0) + 1;int index = line.indexOf("foundme", 0) + 1;

while (index != 0) {while (index != 0) { count++;count++; index = line.indexOf("foundme", index) + 1;index = line.indexOf("foundme", index) + 1; }}}}

System.out.println(count);System.out.println(count);

What is missing What is missing in this code?in this code?

What is missing What is missing in this code?in this code?

Page 22: Basic input-output-v.1.1

Fixing Subtitles – ExampleFixing Subtitles – Example

• Read subtitle file and fix it’s timing:Read subtitle file and fix it’s timing:Scanner fileInput = null;Scanner fileInput = null;PrintStream fileOutput = null;PrintStream fileOutput = null;try {try { // Create scanner with the Cyrillic encoding// Create scanner with the Cyrillic encoding fileInput = new Scanner(new File("source.sub"),fileInput = new Scanner(new File("source.sub"),

"windows-1251");"windows-1251");

// Create PrintWriter with the Cyrillic encoding// Create PrintWriter with the Cyrillic encoding fileOutput = new PrintStream(fileOutput = new PrintStream( "fixed.sub", "windows-1251");"fixed.sub", "windows-1251");

String line;String line;

while (fileInput.hasNextLine()) {while (fileInput.hasNextLine()) { line = fileInput.nextLine();line = fileInput.nextLine(); fileOutput.println(fixLine(line));fileOutput.println(fixLine(line)); }}

// Example continues…// Example continues…

Page 23: Basic input-output-v.1.1

Fixing Subtitles – Example(2)Fixing Subtitles – Example(2)

} catch (FileNotFoundException fnfe) {} catch (FileNotFoundException fnfe) {

System.out.println(fnfe.getMessage());System.out.println(fnfe.getMessage());

} catch (UnsupportedEncodingException uee) {} catch (UnsupportedEncodingException uee) {

System.out.println(uee.getMessage());System.out.println(uee.getMessage());

} finally {} finally { //remember to close the streams//remember to close the streams

if (null != fileInput) {if (null != fileInput) { fileInput.close();fileInput.close(); }} if (null != fileOutput) {if (null != fileOutput) { fileOutput.close();fileOutput.close(); }}}}

Page 24: Basic input-output-v.1.1

Fixing Movie SubtitlesFixing Movie SubtitlesLive DemoLive Demo

Page 25: Basic input-output-v.1.1

SummarySummary

• Streams are the main I/O mechanisms in Streams are the main I/O mechanisms in JavaJava

• Reading text files is done by the Reading text files is done by the ScannerScanner classclass

• Writing text files is done by the Writing text files is done by the PrintStreamPrintStream classclass

• Exceptions are unusual or error conditionsExceptions are unusual or error conditions

• Can be handled by try-catch blocksCan be handled by try-catch blocks

Page 26: Basic input-output-v.1.1

ExercisesExercises

1.1. Write a program that reads a text file and prints Write a program that reads a text file and prints only its odd lines on the console.only its odd lines on the console.

2.2. Write a program that reads a text file and Write a program that reads a text file and inserts line numbers in front of each line. The inserts line numbers in front of each line. The result should be another text file.result should be another text file.

3.3. Write a program that reads a text file containing Write a program that reads a text file containing a list of strings, sorts them and saves them to a list of strings, sorts them and saves them to another text file. Example:another text file. Example:

IvanIvan GeorgeGeorgePeterPeter IvanIvanMariaMaria MariaMariaGeorgeGeorge PeterPeter

Page 27: Basic input-output-v.1.1

Exercises (2)Exercises (2)

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

442 3 3 42 3 3 40 2 3 40 2 3 4 17173 73 7 1 2 1 24 34 3 3 2 3 2

Page 28: Basic input-output-v.1.1

Exercises (3)Exercises (3)

5.5. Write a program that replaces all occurrences Write a program that replaces all occurrences of the substring "start" with the substring of the substring "start" with the substring "finish" in a text file. "finish" in a text file.

6.6. Modify the solution of the previous problem to Modify the solution of the previous problem to replace only whole words.replace only whole words.

7.7. Write a program that extracts from given XML Write a program that extracts from given XML file all the text without the tags. Example:file all the text without the tags. Example:

<?xml version="1.0"><student><name><?xml version="1.0"><student><name>PeshoPesho</name> </name> <age><age>2121</age><interests count="3"><interest> </age><interests count="3"><interest> gamesgames</instrest><interest></instrest><interest>C#C#</instrest><interest> </instrest><interest> JavaJava</instrest></interests></student></instrest></interests></student>

Page 29: Basic input-output-v.1.1

Exercises (4)Exercises (4)

8.8. Write a program that deletes from given text Write a program that deletes from given text file all odd lines. The result should be written file all odd lines. The result should be written to the same file.to the same file.

9.9. Write a program that concatenates two text Write a program that concatenates two text files in another file.files in another file.

10.10. Write a program that deletes from a text file all Write a program that deletes from a text file all words that start with the prefix "test". Words words that start with the prefix "test". Words contain only the symbols 0...9, a...z, A…Z, _.contain only the symbols 0...9, a...z, A…Z, _.

11.11. Write a program that compares two text files Write a program that compares two text files line by line and prints the number of lines that line by line and prints the number of lines that are different.are different.

Page 30: Basic input-output-v.1.1

Exercises (5)Exercises (5)

12.12. Write a program that removes from a text file Write a program that removes from a text file all words that are contained by given another all words that are contained by given another text file. Handle all possible exceptions in your text file. Handle all possible exceptions in your methods.methods.

13.13. Write a program that reads a list of words from Write a program that reads a list of words from a file a file words.txtwords.txt and finds how many times and finds how many times each of the words is contained in another file each of the words is contained in another file test.txttest.txt. The result should be written in the . The result should be written in the file file result.txtresult.txt and the words should be and the words should be sorted by the number of their occurrences in sorted by the number of their occurrences in descending order. Handle all possible descending order. Handle all possible exceptions in your methods.exceptions in your methods.