37
Text Files Text Files Reading and Writing Text Files Reading and Writing Text Files Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com

15. Text Files

Embed Size (px)

DESCRIPTION

Streams Reading from Text Files Writing to Text Files Handling I/O Exceptions when Accessing Files Exercises: Reading and Writing Text Files

Citation preview

Page 1: 15. Text Files

Text FilesText FilesReading and Writing Text FilesReading and Writing Text Files

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 15. Text Files

Table of ContentsTable of Contents

1.1. What is Stream?What is Stream? Stream BasicsStream Basics

2.2. Reading Text FilesReading Text Files The The StreamReaderStreamReader Class Class

3.3. Writing Text FilesWriting Text Files The The StreamStreamWritWriterer Class Class

4.4. Handling I/O ExceptionsHandling I/O Exceptions

Page 3: 15. Text Files

What Is Stream?What Is Stream?Streams Basic ConceptsStreams Basic Concepts

Page 4: 15. Text Files

What is Stream?What is Stream? Stream is the natural way to Stream is the natural way to

transfer data in the computer transfer data in the computer worldworld

To read or write a file, we open a To read or write a file, we open a stream connected to the file and stream connected to the file and access the data through the access the data through the streamstream Input streamInput stream

Output streamOutput stream

Page 5: 15. Text Files

Streams BasicsStreams Basics Streams are used for reading and Streams are used for reading and

writing data into and from deviceswriting data into and from devices Streams are Streams are ordered sequences of bytesordered sequences of bytes

Provide consecutive access to its Provide consecutive access to its elementselements

Different types of streams are available Different types of streams are available to access different data sources:to access different data sources: File access, network access, memory File access, network access, memory

streams and othersstreams and others Streams are open before using them and Streams are open before using them and

closed after thatclosed after that

Page 6: 15. Text Files

Reading Text Reading Text FilesFiles

Using theUsing the StreamReaderStreamReader Class Class

Page 7: 15. Text Files

The The StreamReaderStreamReader Class Class

System.IO.StreamReaderSystem.IO.StreamReader The easiest way to read a text fileThe easiest way to read a text file

Implements methods for reading text Implements methods for reading text lines and sequences of characterslines and sequences of characters

Constructed by file name or other Constructed by file name or other streamstream

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

Works like Works like Console.Read()Console.Read() / / ReadLine()ReadLine() but over text files but over text files

Page 8: 15. Text Files

StreamReaderStreamReader Methods Methods new StreamReader(fileName)new StreamReader(fileName)

Constructor for creating reader from given Constructor for creating reader from given filefile

ReadLine()ReadLine() Reads a single text line from the streamReads a single text line from the stream Returns Returns nullnull when end-of-file is reached when end-of-file is reached

ReadToEnd()ReadToEnd() Reads all the text until the end of the Reads all the text until the end of the

streamstream Close()Close()

Closes the stream readerCloses the stream reader

Page 9: 15. Text Files

Reading a text file and printing its Reading a text file and printing its content to content to the console:the console:

Specifying the text encoding:Specifying the text encoding:

Reading a Text FileReading a Text File

StreamReader reader = new StreamReader reader = new StreamReader("test.txt");StreamReader("test.txt");string fileContents = streamReader.ReadToEnd();string fileContents = streamReader.ReadToEnd();Console.WriteLine(fileContents);Console.WriteLine(fileContents);streamReader.Close();streamReader.Close();

StreamReader reader = new StreamReader(StreamReader reader = new StreamReader( "cyr.txt", Encoding.GetEncoding(""cyr.txt", Encoding.GetEncoding("windows-windows-12511251"));"));// Read the file contents here ...// Read the file contents here ...reader.Close();reader.Close();

Page 10: 15. Text Files

Using Using StreamReaderStreamReader – – PracticesPractices

The The StreamReaderStreamReader instances should instances should always be closed by calling the always be closed by calling the Close()Close() methodmethod Otherwise system resources can be lostOtherwise system resources can be lost

In C# the preferable way to close In C# the preferable way to close streams and readers is by the "streams and readers is by the "usingusing" " constructionconstruction

It automatically calls the It automatically calls the Close()Close()after after the the usingusing construction is completed construction is completed

using (<stream object>) using (<stream object>) {{ // Use the stream here. It will be closed at // Use the stream here. It will be closed at the endthe end}}

Page 11: 15. Text Files

Reading a Text File – Reading a Text File – ExampleExample

Read and display a text file line by Read and display a text file line by line:line:StreamReader reader =StreamReader reader = new StreamReader("somefile.txt");new StreamReader("somefile.txt");using (reader)using (reader){{ int lineNumber = 0;int lineNumber = 0; string line = reader.ReadLine();string line = reader.ReadLine(); while (line != null)while (line != null) {{ lineNumber++;lineNumber++; Console.WriteLine("Line {0}: {1}",Console.WriteLine("Line {0}: {1}", lineNumber, line);lineNumber, line); line = reader.ReadLine();line = reader.ReadLine(); }}}}

Page 12: 15. Text Files

Reading Text Reading Text FilesFilesLive DemoLive Demo

Page 13: 15. Text Files

Writing Text FilesWriting Text FilesUsing the Using the StreamStreamWriterWriter Class Class

Page 14: 15. Text Files

The The StreamWriterStreamWriter Class Class System.IO.StreamWriterSystem.IO.StreamWriter

Similar to Similar to StringReaderStringReader, but instead , but instead of reading, it provides writing of reading, it provides writing functionalityfunctionality

Constructed by file name or other Constructed by file name or other streamstream

Can define encodingCan define encoding

For Cyrillic use "For Cyrillic use "windows-1251windows-1251""StreamWriter streamWriter = new StreamWriter streamWriter = new

StreamWriter("test.txt",StreamWriter("test.txt",

false, Encoding.GetEncoding("windows-1251"));false, Encoding.GetEncoding("windows-1251"));

StreamWriter streamWriter = new StreamWriter streamWriter = new

StreamWriter("test.txt");StreamWriter("test.txt");

Page 15: 15. Text Files

StreamWriterStreamWriter Methods Methods Write()Write()

Writes string or other object to the Writes string or other object to the streamstream

Like Like Console.WriteConsole.Write()() WriteLineWriteLine()()

Like Like Console.WriteConsole.WriteLine()Line() AutoFlushAutoFlush

Indicates whether to flush the Indicates whether to flush the internal buffer after each writinginternal buffer after each writing

Page 16: 15. Text Files

Writing to a Text File – Writing to a Text File – ExampleExample

Create text file named "Create text file named "numbers.txtnumbers.txt" " and print in it the numbers from 1 to and print in it the numbers from 1 to 20 (one per line):20 (one per line):StreamWriter streamWriter = StreamWriter streamWriter =

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

using (streamWriter)using (streamWriter)

{{

for (int number = 1; number <= 20; number++)for (int number = 1; number <= 20; number++)

{{

streamWriter.WriteLine(number);streamWriter.WriteLine(number);

}}

}}

Page 17: 15. Text Files

Writing Text FilesWriting Text FilesLive DemoLive Demo

Page 18: 15. Text Files

Handling I/O Handling I/O ExceptionsExceptionsIntroductionIntroduction

Page 19: 15. Text Files

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 of the program that disrupts the normal flow of instructions“ – definition by Googleflow of instructions“ – definition by Google

Occurs when an operation can not be Occurs when an operation can not be completedcompleted

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

I/O operations throw exceptions when I/O operations throw exceptions when operation cannot be performed (e.g. operation cannot be performed (e.g. missing file)missing file)

When an exception is thrown, all operations When an exception is thrown, all operations after it are not processedafter it are not processed

Page 20: 15. Text Files

How to Handle How to Handle Exceptions?Exceptions?

Using Using try{}try{},, catch{}catch{} and and finally{}finally{} blocks:blocks:trytry

{{

// Some exception is thrown here// Some exception is thrown here

}}

catch (<exception type>)catch (<exception type>)

{{

// Exception is handled here // Exception is handled here

}}

finallyfinally

{{

// The code here is always executed, no// The code here is always executed, no

// matter if an exception has occurred or not // matter if an exception has occurred or not

}}

Page 21: 15. Text Files

Catching ExceptionsCatching Exceptions Catch block specifies the type of Catch block specifies the type of

exceptions that is caughtexceptions that is caught If If catchcatch doesn’t specify its type, it doesn’t specify its type, it

catches all types of exceptionscatches all types of exceptions

trytry{{ StreamReader reader = new StreamReader reader = new StreamReader("somefile.txt");StreamReader("somefile.txt"); Console.WriteLine("File successfully open.");Console.WriteLine("File successfully open.");} } catch (FileNotFoundException)catch (FileNotFoundException){{ Console.Error.WriteLine("Can not find Console.Error.WriteLine("Can not find 'somefile.txt'.");'somefile.txt'.");}}

Page 22: 15. Text Files

Handling Handling Exceptions When Exceptions When

Opening a FileOpening a Filetrytry{{ StreamReader streamReader = new StreamReader(StreamReader streamReader = new StreamReader( "c:\\NotExistingFileName.txt");"c:\\NotExistingFileName.txt");}}catch (System.NullReferenceException exc)catch (System.NullReferenceException exc){{ Console.WriteLine(exc.Message);Console.WriteLine(exc.Message);}}catch (System.IO.FileNotFoundException exc)catch (System.IO.FileNotFoundException exc){{ Console.WriteLine(Console.WriteLine( "File {0} is not found!", exc.FileName);"File {0} is not found!", exc.FileName);}}catchcatch{{ Console.WriteLine("Fatal error occurred.");Console.WriteLine("Fatal error occurred.");}}

Page 23: 15. Text Files

Handling Handling I/O I/O

ExceptionExceptionssLive DemoLive Demo

Page 24: 15. Text Files

Reading and Reading and Writing Text Writing Text

FilesFilesMore ExamplesMore Examples

Page 25: 15. Text Files

Counting Word Counting Word Occurrences – Occurrences –

ExampleExample Counting the number of Counting the number of

occurrences of the word "occurrences of the word "foundmefoundme" " in a text file:in a text file:StreamReader streamReader = StreamReader streamReader = new StreamReader(@"..\..\somefile.txt");new StreamReader(@"..\..\somefile.txt");int count = 0;int count = 0;string text = streamReader.ReadToEnd();string text = streamReader.ReadToEnd();int index = text.IndexOf("foundme", 0);int index = text.IndexOf("foundme", 0);while (index != -1)while (index != -1){{ count++;count++; index = text.IndexOf("foundme", index + 1);index = text.IndexOf("foundme", index + 1);}}Console.WriteLine(count);Console.WriteLine(count); What is What is

missing in missing in this code?this code?

Page 26: 15. Text Files

Counting Word Counting Word OccurrencesOccurrences

Live DemoLive Demo

Page 27: 15. Text Files

Reading Subtitles – Reading Subtitles – Example Example

..........

{2757}{2803} Allen, Bomb Squad, Special Services...{2757}{2803} Allen, Bomb Squad, Special Services...{2804}{2874} State Police and the FBI!{2804}{2874} State Police and the FBI!{2875}{2963} Lieutenant! I want you to go to St. John's {2875}{2963} Lieutenant! I want you to go to St. John's Emergency...Emergency...{2964}{3037} in case we got any walk-ins from the {2964}{3037} in case we got any walk-ins from the street.street.{3038}{3094} Kramer, get the city engineer!{3038}{3094} Kramer, get the city engineer!{3095}{3142} I gotta find out a damage report. It's very {3095}{3142} I gotta find out a damage report. It's very important.important.{3171}{3219} Who the hell would want to blow up a {3171}{3219} Who the hell would want to blow up a department store?department store?

..........

We are given a standard movie We are given a standard movie subtitles file:subtitles file:

Page 28: 15. Text Files

Fixing Subtitles – Fixing Subtitles – ExampleExample

Read subtitles file and fix it’s timing:Read subtitles file and fix it’s timing:

static void Main()static void Main(){{ trytry {{ // Obtaining the Cyrillic encoding// Obtaining the Cyrillic encoding System.Text.Encoding encodingCyr =System.Text.Encoding encodingCyr = System.Text.Encoding.GetEncoding(1251);System.Text.Encoding.GetEncoding(1251);

// Create reader with the Cyrillic encoding// Create reader with the Cyrillic encoding StreamReader streamReader =StreamReader streamReader = new StreamReader("source.sub", encodingCyr);new StreamReader("source.sub", encodingCyr);

// Create writer with the Cyrillic encoding// Create writer with the Cyrillic encoding StreamWriter streamWriter =StreamWriter streamWriter = new StreamWriter("fixed.sub", new StreamWriter("fixed.sub", false, encodingCyr);false, encodingCyr);

(example continues)(example continues)

Page 29: 15. Text Files

Fixing Subtitles – Fixing Subtitles – ExampleExample

trytry {{ string line;string line; while (while ( (line = streamReader.ReadLine()) != null)(line = streamReader.ReadLine()) != null) {{ streamWriter.WriteLine(FixLine(line));streamWriter.WriteLine(FixLine(line)); }} }} finallyfinally {{ streamReader.Close();streamReader.Close(); streamWriter.Close();streamWriter.Close(); }} }} catch (System.Exception exc)catch (System.Exception exc) {{ Console.WriteLine(exc.Message);Console.WriteLine(exc.Message); }}}}

FixLine(line)FixLine(line) perform fixes on perform fixes on the time offsets:the time offsets:

multiplication multiplication or/and addition or/and addition with constantwith constant

Page 30: 15. Text Files

Fixing Movie Fixing Movie SubtitlesSubtitles

Live DemoLive Demo

Page 31: 15. Text Files

SummarySummary Streams are the main I/O mechanismsStreams are the main I/O mechanisms

in .NETin .NET The The StreamReaderStreamReader class and class and ReadLine()ReadLine()

method are used to read text filesmethod are used to read text files The The StreamWriterStreamWriter class and class and WriteLine()WriteLine()

method are used to write text filesmethod are used to write text files Exceptions are unusual events or error Exceptions are unusual events or error

conditionsconditions Can be handled by Can be handled by try-catch-finallytry-catch-finally

blocksblocks

Page 32: 15. Text Files

Text FilesText Files

QuestioQuestions?ns?

http://academy.telerik.com

Page 33: 15. Text Files

ExercisesExercises1.1. Write a program that reads a text file and Write a program that reads a text file and

prints on the console its odd lines.prints on the console its odd lines.

2.2. Write a program that concatenates two text Write a program that concatenates two text files into another text file.files into another text file.

3.3. 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 of its inserts line numbers in front of each of its lines. The result should be written to lines. The result should be written to another text file.another text file.

4.4. Write a program that compares two text Write a program that compares two text files line by line and prints the number of files line by line and prints the number of lines that are the same and the number of lines that are the same and the number of lines that are different. Assume the files lines that are different. Assume the files have equal number of lines.have equal number of lines.

Page 34: 15. Text Files

Exercises (2)Exercises (2)5.5. Write a program that reads a text file Write a program that reads a text file

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

44

2 3 3 42 3 3 4

0 2 3 40 2 3 4 1717

3 7 3 7 1 21 2

4 3 4 3 3 23 2

Page 35: 15. Text Files

Exercises (3)Exercises (3)6.6. Write a program that reads a text file Write a program that reads a text file

containing a list of strings, sorts them and containing a list of strings, sorts them and saves them to another text file. Example:saves them to another text file. Example:

IvanIvan GeorgeGeorge

PeterPeter IvanIvan

MariaMaria MariaMaria

GeorgeGeorge PeterPeter

7.7. Write a program that replaces all Write a program that replaces all occurrences of the substring "start" with occurrences of the substring "start" with the substring "finish" in a text file. Ensure the substring "finish" in a text file. Ensure it will work with large files (e.g. 100 MB).it will work with large files (e.g. 100 MB).

8.8. Modify the solution of the previous problem Modify the solution of the previous problem to replace only whole words (not to replace only whole words (not substrings).substrings).

Page 36: 15. Text Files

Exercises (4)Exercises (4)9.9. Write a program that deletes from given text Write a program that deletes from given text

file all odd lines. The result should be in the file all odd lines. The result should be in the same file.same file.

10.10. 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:

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

<?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>

Page 37: 15. Text Files

Exercises (5)Exercises (5)

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

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