Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer www.nakov.com.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

Reading and Writing Text Files Svetlin Nakov Telerik Corporation
HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Accessing SQL Server and MySQL – Live Demo Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Creating E/R Diagrams with SQL Server Management Studio and MySQL Workbench Svetlin Nakov Telerik Software Academy Manager Technical.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Telerik Software Academy End-to-end JavaScript Applications.
What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Course Overview Doncho Minkov Telerik Software Academy Technical Trainer
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Presentation transcript:

Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer

1. What is Stream?  Stream Basics 2. Reading Text Files  The StreamReader Class 3. Writing Text Files  The StreamWriter Class 4. Handling I/O Exceptions 2

Streams Basic Concepts

 Stream is the natural way to transfer data in the computer world  To read or write a file, we open a stream connected to the file and access the data through the stream Input stream Output stream 4

 Streams are used for reading and writing data into and from devices  Streams are ordered sequences of bytes  Provide consecutive access to its elements  Different types of streams are available to access different data sources:  File access, network access, memory streams and others  Streams are open before using them and closed after that 5

Using the StreamReader Class

 System.IO.StreamReader  The easiest way to read a text file  Implements methods for reading text lines and sequences of characters  Constructed by file name or other stream  Can specify the text encoding (for Cyrillic use windows-1251 )  Works like Console.Read() / ReadLine() but over text files 7

 new StreamReader(fileName)  Constructor for creating reader from given file  ReadLine()  Reads a single text line from the stream  Returns null when end-of-file is reached  ReadToEnd()  Reads all the text until the end of the stream  Close()  Closes the stream reader 8

 Reading a text file and printing its content to the console:  Specifying the text encoding: StreamReader reader = new StreamReader("test.txt"); string fileContents = reader.ReadToEnd(); Console.WriteLine(fileContents);streamReader.Close(); StreamReader reader = new StreamReader( "cyr.txt", Encoding.GetEncoding("windows-1251")); "cyr.txt", Encoding.GetEncoding("windows-1251")); // Read the file contents here... reader.Close(); 9

 The StreamReader instances should always be closed by calling the Close() method  Otherwise system resources can be lost  In C# the preferable way to close streams and readers is by the " using " construction  It automatically calls the Close() after the using construction is completed using ( ) { // Use the stream here. It will be closed at the end // Use the stream here. It will be closed at the end} 10

 Read and display a text file line by line: StreamReader reader = new StreamReader("somefile.txt"); new StreamReader("somefile.txt"); 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(); }} 11

Live Demo

Using the StreamWriter Class

 System.IO.StreamWriter  Similar to StreamReader, but instead of reading, it provides writing functionality  Constructed by file name or other stream  Can define encoding  For Cyrillic use " windows-1251 " StreamWriter streamWriter = new StreamWriter("test.txt", new StreamWriter("test.txt", false, Encoding.GetEncoding("windows-1251")); false, Encoding.GetEncoding("windows-1251")); StreamWriter streamWriter = new StreamWriter("test.txt"); new StreamWriter("test.txt"); 14

 Write()  Writes string or other object to the stream  Like Console.Write()  WriteLine()  Like Console.WriteLine()  Flush()  Flushes the internal buffers to the hard drive  AutoFlush  Flush the internal buffer after each writing 15

 Create text file named " numbers.txt " and print in it the numbers from 1 to 20 (one per line): StreamWriter streamWriter = new StreamWriter("numbers.txt"); new StreamWriter("numbers.txt"); using (streamWriter) { for (int number = 1; number <= 20; number++) for (int number = 1; number <= 20; number++) { streamWriter.WriteLine(number); streamWriter.WriteLine(number); }} 16

Live Demo

Introduction

 "An event that occurs during the execution of the program that disrupts the normal flow of instructions“ – definition by Google  Occurs when an operation can not be completed  Exceptions tell that something unusual has happened, e. g. error or unexpected event  I/O operations throw exceptions when operation cannot be performed (e.g. missing file)  When an exception is thrown, all operations after it are not processed 19

 Using try{}, catch{} and finally{} blocks: try{ // Some exception is thrown here } // Some exception is thrown here } catch ( ) { // Exception is handled here }finally{ // 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 } 20

 Catch block specifies the type of exceptions that is caught  If catch doesn’t specify its type, it catches all types of exceptions try{ StreamReader reader = new StreamReader("file.txt"); StreamReader reader = new StreamReader("file.txt"); Console.WriteLine("File successfully open."); Console.WriteLine("File successfully open.");} catch (FileNotFoundException) { Console.Error.WriteLine( Console.Error.WriteLine( "Can not find 'somefile.txt'."); "Can not find 'somefile.txt'.");} 21

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

Live Demo

More Examples

 Counting the number of occurrences of the word " foundme " in a text file: StreamReader streamReader = new new int count = 0; string text = streamReader.ReadToEnd(); int index = text.IndexOf("foundme", 0); while (index != -1) { count++; count++; index = text.IndexOf("foundme", index + 1); index = text.IndexOf("foundme", index + 1);}Console.WriteLine(count); What is missing in this code? 25

Live Demo

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

 Read subtitles file and fix it’s timing: static void Main() { try try { // 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) 28

try try { string line; string line; while ( while ( (line = streamReader.ReadLine()) != null) (line = streamReader.ReadLine()) != null) { streamWriter.WriteLine(FixLine(line)); streamWriter.WriteLine(FixLine(line)); } } finally finally { 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) perform fixes on the time offsets: multiplication or/and addition with constant 29

Live Demo

 Streams are the main I/O mechanisms in.NET  The StreamReader class and ReadLine() method are used to read text files  The StreamWriter class and WriteLine() method are used to write text files  Always put file handling in using(…) block  Exceptions are unusual events or error conditions  Can be handled by try-catch-finally blocks 31

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

1. Write a program that reads a text file and prints on the console its odd lines. 2. Write a program that concatenates two text files into another text file. 3. Write a program that reads a text file and inserts line numbers in front of each of its lines. The result should be written to another text file. 4. Write a program that compares two text files line by line and prints the number of lines that are the same and the number of lines that are different. Assume the files have equal number of lines. 33

5. 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. Each of the next N lines contain N numbers separated by space. The output should be a single number in a separate text file. Example:

6. Write a program that reads a text file containing a list of strings, sorts them and saves them to another text file. Example: IvanGeorge PeterIvan MariaMaria GeorgePeter 7. Write a program that replaces all occurrences of the substring "start" with the substring "finish" in a text file. Ensure it will work with large files (e.g. 100 MB). 8. Modify the solution of the previous problem to replace only whole words (not substrings). 35

9. Write a program that deletes from given text file all odd lines. The result should be in the same file. 10. Write a program that extracts from given XML file all the text without the tags. Example: 11. 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, _. Pesho 21 Games C# Java 36

12. Write a program that removes from a text file all words listed in given another text file. Handle all possible exceptions in your methods. 13. 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. 37

 “C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com