SlideShare una empresa de Scribd logo
1 de 37
Text Files
Reading andWritingText Files
Svetlin Nakov
Telerik Corporation
www.telerik.com
Table of Contents
1. What is Stream?
 Stream Basics
2. ReadingText Files
 The StreamReader Class
3. WritingText Files
 The StreamWriter Class
4. Handling I/O Exceptions
What Is Stream?
Streams Basic Concepts
What is Stream?
 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
Streams Basics
 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
ReadingText Files
Using the StreamReader Class
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
StreamReader Methods
 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
 Reading a text file and printing its content to
the console:
 Specifying the text encoding:
Reading aText File
StreamReader reader = new StreamReader("test.txt");
string fileContents = streamReader.ReadToEnd();
Console.WriteLine(fileContents);
streamReader.Close();
StreamReader reader = new StreamReader(
"cyr.txt", Encoding.GetEncoding("windows-1251"));
// Read the file contents here ...
reader.Close();
Using StreamReader – Practices
 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 (<stream object>)
{
// Use the stream here. It will be closed at the end
}
Reading aText File – Example
 Read and display a text file line by line:
StreamReader reader =
new StreamReader("somefile.txt");
using (reader)
{
int lineNumber = 0;
string line = reader.ReadLine();
while (line != null)
{
lineNumber++;
Console.WriteLine("Line {0}: {1}",
lineNumber, line);
line = reader.ReadLine();
}
}
ReadingText Files
Live Demo
WritingText Files
Using the StreamWriter Class
The StreamWriter Class
 System.IO.StreamWriter
 Similar to StringReader, 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",
false, Encoding.GetEncoding("windows-1251"));
StreamWriter streamWriter = new StreamWriter("test.txt");
StreamWriter Methods
 Write()
 Writes string or other object to the stream
 Like Console.Write()
 WriteLine()
 Like Console.WriteLine()
 AutoFlush
 Indicates whether to flush the internal buffer
after each writing
Writing to aText File – Example
 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");
using (streamWriter)
{
for (int number = 1; number <= 20; number++)
{
streamWriter.WriteLine(number);
}
}
WritingText Files
Live Demo
Handling I/O Exceptions
Introduction
What is Exception?
 "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 was
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
How to Handle Exceptions?
 Using try{}, catch{} and finally{} blocks:
try
{
// Some exception is thrown here
}
catch (<exception type>)
{
// Exception is handled here
}
finally
{
// The code here is always executed, no
// matter if an exception has occurred or not
}
Catching Exceptions
 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("somefile.txt");
Console.WriteLine("File successfully open.");
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("Can not find 'somefile.txt'.");
}
Handling Exceptions
When Opening a File
try
{
StreamReader streamReader = new StreamReader(
"c:NotExistingFileName.txt");
}
catch (System.NullReferenceException exc)
{
Console.WriteLine(exc.Message);
}
catch (System.IO.FileNotFoundException exc)
{
Console.WriteLine(
"File {0} is not found!", exc.FileName);
}
catch
{
Console.WriteLine("Fatal error occurred.");
}
Handling I/O
Exceptions
Live Demo
Reading and
WritingText Files
More Examples
Counting Word
Occurrences – Example
 Counting the number of occurrences of the
word "foundme" in a text file:
StreamReader streamReader =
new StreamReader(@"....somefile.txt");
int count = 0;
string text = streamReader.ReadToEnd();
int index = text.IndexOf("foundme", 0);
while (index != -1)
{
count++;
index = text.IndexOf("foundme", index + 1);
}
Console.WriteLine(count);
What is missing
in this code?
CountingWord Occurrences
Live Demo
Reading Subtitles – Example
.....
{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:
Fixing Subtitles – Example
 Read subtitles file and fix it’s timing:
static void Main()
{
try
{
// Obtaining the Cyrillic encoding
System.Text.Encoding encodingCyr =
System.Text.Encoding.GetEncoding(1251);
// Create reader with the Cyrillic encoding
StreamReader streamReader =
new StreamReader("source.sub", encodingCyr);
// Create writer with the Cyrillic encoding
StreamWriter streamWriter =
new StreamWriter("fixed.sub",
false, encodingCyr);
(example continues)
Fixing Subtitles – Example
try
{
string line;
while (
(line = streamReader.ReadLine()) != null)
{
streamWriter.WriteLine(FixLine(line));
}
}
finally
{
streamReader.Close();
streamWriter.Close();
}
}
catch (System.Exception exc)
{
Console.WriteLine(exc.Message);
}
}
FixLine(line) perform
fixes on the time offsets:
multiplication or/and
addition with constant
Fixing Movie Subtitles
Live Demo
Summary
 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
 Exceptions are unusual events or error
conditions
 Can be handled by try-catch-finally blocks
Text Files
Questions?
http://academy.telerik.com
Exercises
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.
Exercises (2)
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:
4
2 3 3 4
0 2 3 4 17
3 7 1 2
4 3 3 2
Exercises (3)
6. 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
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).
Exercises (4)
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, _.
<?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>
Exercises (5)
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.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Java I/O
Java I/OJava I/O
Java I/O
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java stream
Java streamJava stream
Java stream
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Stream
StreamStream
Stream
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
Io streams
Io streamsIo streams
Io streams
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Basic of java
Basic of javaBasic of java
Basic of java
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
IO In Java
IO In JavaIO In Java
IO In Java
 
File handling
File handlingFile handling
File handling
 

Destacado

Propuestas del consejo de administración de Sniace
Propuestas del consejo de administración de SniacePropuestas del consejo de administración de Sniace
Propuestas del consejo de administración de SniaceDiego Gutiérrez
 
Presentataion Oil&Gas Telecommunications Conference - Radio LInk Project
Presentataion  Oil&Gas Telecommunications Conference - Radio LInk Project Presentataion  Oil&Gas Telecommunications Conference - Radio LInk Project
Presentataion Oil&Gas Telecommunications Conference - Radio LInk Project Andrea Vallavanti
 
EMD Serono Analysis - MBA Organizational Behavior Class
EMD Serono Analysis - MBA Organizational Behavior ClassEMD Serono Analysis - MBA Organizational Behavior Class
EMD Serono Analysis - MBA Organizational Behavior ClassSam Bishop
 
Book Review - Learning Censorship
Book Review - Learning CensorshipBook Review - Learning Censorship
Book Review - Learning CensorshipLuke Sheahan
 
Enersys Case Study - MBA Strategic Mgmt Class
Enersys Case Study - MBA Strategic Mgmt ClassEnersys Case Study - MBA Strategic Mgmt Class
Enersys Case Study - MBA Strategic Mgmt ClassSam Bishop
 
Bad Eggs 2 Cheats
Bad Eggs 2 CheatsBad Eggs 2 Cheats
Bad Eggs 2 Cheatsmobilefun
 
пейзажная лирика поэтов 19 века
пейзажная лирика поэтов 19 векапейзажная лирика поэтов 19 века
пейзажная лирика поэтов 19 векаl1980larisa
 
Lean Manufacturing Overview - MBA Consulting Class
Lean Manufacturing Overview - MBA Consulting ClassLean Manufacturing Overview - MBA Consulting Class
Lean Manufacturing Overview - MBA Consulting ClassSam Bishop
 
power generation through speed breaker
power generation through speed breaker power generation through speed breaker
power generation through speed breaker Ranjan Kumar Thakur
 
Infiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing ClassInfiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing ClassSam Bishop
 
power generation through speed breaker
power generation through speed breaker power generation through speed breaker
power generation through speed breaker Ranjan Kumar Thakur
 

Destacado (14)

Propuestas del consejo de administración de Sniace
Propuestas del consejo de administración de SniacePropuestas del consejo de administración de Sniace
Propuestas del consejo de administración de Sniace
 
Суфиксација
СуфиксацијаСуфиксација
Суфиксација
 
Presentataion Oil&Gas Telecommunications Conference - Radio LInk Project
Presentataion  Oil&Gas Telecommunications Conference - Radio LInk Project Presentataion  Oil&Gas Telecommunications Conference - Radio LInk Project
Presentataion Oil&Gas Telecommunications Conference - Radio LInk Project
 
HGFD
HGFDHGFD
HGFD
 
Presentation
PresentationPresentation
Presentation
 
EMD Serono Analysis - MBA Organizational Behavior Class
EMD Serono Analysis - MBA Organizational Behavior ClassEMD Serono Analysis - MBA Organizational Behavior Class
EMD Serono Analysis - MBA Organizational Behavior Class
 
Book Review - Learning Censorship
Book Review - Learning CensorshipBook Review - Learning Censorship
Book Review - Learning Censorship
 
Enersys Case Study - MBA Strategic Mgmt Class
Enersys Case Study - MBA Strategic Mgmt ClassEnersys Case Study - MBA Strategic Mgmt Class
Enersys Case Study - MBA Strategic Mgmt Class
 
Bad Eggs 2 Cheats
Bad Eggs 2 CheatsBad Eggs 2 Cheats
Bad Eggs 2 Cheats
 
пейзажная лирика поэтов 19 века
пейзажная лирика поэтов 19 векапейзажная лирика поэтов 19 века
пейзажная лирика поэтов 19 века
 
Lean Manufacturing Overview - MBA Consulting Class
Lean Manufacturing Overview - MBA Consulting ClassLean Manufacturing Overview - MBA Consulting Class
Lean Manufacturing Overview - MBA Consulting Class
 
power generation through speed breaker
power generation through speed breaker power generation through speed breaker
power generation through speed breaker
 
Infiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing ClassInfiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing Class
 
power generation through speed breaker
power generation through speed breaker power generation through speed breaker
power generation through speed breaker
 

Similar a 15. text files

File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File ConceptsANUSUYA S
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++Teguh Nugraha
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in javaJayasankarPR2
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
ASP.NET Session 8
ASP.NET Session 8ASP.NET Session 8
ASP.NET Session 8Sisir Ghosh
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docxtheodorelove43763
 

Similar a 15. text files (20)

Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
srgoc
srgocsrgoc
srgoc
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
ASP.NET Session 8
ASP.NET Session 8ASP.NET Session 8
ASP.NET Session 8
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Data file handling
Data file handlingData file handling
Data file handling
 
Xml writers
Xml writersXml writers
Xml writers
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 

Último

Call girls in Vashi Service 7738596112 Free Delivery 24x7 at Your Doorstep
Call girls in Vashi Service 7738596112 Free Delivery 24x7 at Your DoorstepCall girls in Vashi Service 7738596112 Free Delivery 24x7 at Your Doorstep
Call girls in Vashi Service 7738596112 Free Delivery 24x7 at Your Doorstepmitaliverma221
 
{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...
{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...
{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...Pooja Nehwal
 
Introduction to Fashion Designing for all
Introduction to Fashion Designing for allIntroduction to Fashion Designing for all
Introduction to Fashion Designing for allMuhammadDanishAwan1
 
Tirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tirunelveli
Tirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime TirunelveliTirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tirunelveli
Tirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tirunelvelimeghakumariji156
 
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries""Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"Aarisha Shaikh
 
UNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human BeingUNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human BeingChandrakantDivate1
 
Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...
Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...
Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...rajveermohali2022
 
Ladies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdfLadies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdfShort Good Quotes
 
Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...
Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...
Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...rajveermohali2022
 
9867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x7
9867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x79867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x7
9867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x7Pooja Nehwal
 
Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...
Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...
Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...Nitya salvi
 
Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...
Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...
Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...rajveerescorts2022
 
Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...
Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...
Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...minkseocompany
 
Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...
Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...
Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...Pooja Nehwal
 
Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...
Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...
Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...Nitya salvi
 
Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...
Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...
Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...rajveerescorts2022
 
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...mitaliverma221
 
Tumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tumkur
Tumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime TumkurTumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tumkur
Tumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tumkurmeghakumariji156
 
I am Independent Call girl in noida at chepest price Call Me 8826255397
I am Independent Call girl in noida at chepest price Call Me 8826255397I am Independent Call girl in noida at chepest price Call Me 8826255397
I am Independent Call girl in noida at chepest price Call Me 8826255397Riya Singh
 

Último (20)

Call girls in Vashi Service 7738596112 Free Delivery 24x7 at Your Doorstep
Call girls in Vashi Service 7738596112 Free Delivery 24x7 at Your DoorstepCall girls in Vashi Service 7738596112 Free Delivery 24x7 at Your Doorstep
Call girls in Vashi Service 7738596112 Free Delivery 24x7 at Your Doorstep
 
{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...
{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...
{ Pooja 9892124323 } girls birds call girls netflix funny names to call girls...
 
Introduction to Fashion Designing for all
Introduction to Fashion Designing for allIntroduction to Fashion Designing for all
Introduction to Fashion Designing for all
 
Tirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tirunelveli
Tirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime TirunelveliTirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tirunelveli
Tirunelveli Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tirunelveli
 
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries""Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
"Paltr Packaging: Streamlined Order Process for Seamless Deliveries"
 
UNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human BeingUNIVERSAL HUMAN VALUES -Harmony in the Human Being
UNIVERSAL HUMAN VALUES -Harmony in the Human Being
 
Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...
Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...
Kharar Call Girls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort Se...
 
Ladies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdfLadies kitty party invitation messages and greetings.pdf
Ladies kitty party invitation messages and greetings.pdf
 
Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...
Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...
Zirakpur Call GIrls Service✔️ 9915851334 ✔️Call Now Ranveer📲 Zirakpur Escort ...
 
9867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x7
9867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x79867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x7
9867746289 - Payal Mehta Book Call Girls in Versova and escort services 24x7
 
@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait
@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait
@Abortion clinic tablets Kuwait (+918133066128) Abortion Pills IN Kuwait
 
Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...
Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...
Escorts Service Model Basti 👉 Just CALL ME: 8617697112 💋 Call Out Call Both W...
 
Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...
Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...
Zirakpur Call Girls ✅ Just Call ☎ 9878799926☎ Call Girls Service In Mohali Av...
 
Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...
Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...
Top 20: Best & Hottest Russian Pornstars Right Now (2024) Russian Porn Stars ...
 
Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...
Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...
Mahim Call Girls in Bandra 7738631006, Sakinaka Call Girls agency, Kurla Call...
 
Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...
Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...
Call Girls In Jamnagar Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service Enj...
 
Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...
Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...
Call Girls In Mohali ☎ 9915851334☎ Just Genuine Call Call Girls Mohali 🧿Elite...
 
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...
Call Girls In Mumbai Just Genuine Call ☎ 7738596112✅ Call Girl Andheri East P...
 
Tumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tumkur
Tumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime TumkurTumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tumkur
Tumkur Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tumkur
 
I am Independent Call girl in noida at chepest price Call Me 8826255397
I am Independent Call girl in noida at chepest price Call Me 8826255397I am Independent Call girl in noida at chepest price Call Me 8826255397
I am Independent Call girl in noida at chepest price Call Me 8826255397
 

15. text files

  • 1. Text Files Reading andWritingText Files Svetlin Nakov Telerik Corporation www.telerik.com
  • 2. Table of Contents 1. What is Stream?  Stream Basics 2. ReadingText Files  The StreamReader Class 3. WritingText Files  The StreamWriter Class 4. Handling I/O Exceptions
  • 3. What Is Stream? Streams Basic Concepts
  • 4. What is Stream?  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
  • 5. Streams Basics  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
  • 6. ReadingText Files Using the StreamReader Class
  • 7. 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
  • 8. StreamReader Methods  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
  • 9.  Reading a text file and printing its content to the console:  Specifying the text encoding: Reading aText File StreamReader reader = new StreamReader("test.txt"); string fileContents = streamReader.ReadToEnd(); Console.WriteLine(fileContents); streamReader.Close(); StreamReader reader = new StreamReader( "cyr.txt", Encoding.GetEncoding("windows-1251")); // Read the file contents here ... reader.Close();
  • 10. Using StreamReader – Practices  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 (<stream object>) { // Use the stream here. It will be closed at the end }
  • 11. Reading aText File – Example  Read and display a text file line by line: StreamReader reader = new StreamReader("somefile.txt"); using (reader) { int lineNumber = 0; string line = reader.ReadLine(); while (line != null) { lineNumber++; Console.WriteLine("Line {0}: {1}", lineNumber, line); line = reader.ReadLine(); } }
  • 13. WritingText Files Using the StreamWriter Class
  • 14. The StreamWriter Class  System.IO.StreamWriter  Similar to StringReader, 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", false, Encoding.GetEncoding("windows-1251")); StreamWriter streamWriter = new StreamWriter("test.txt");
  • 15. StreamWriter Methods  Write()  Writes string or other object to the stream  Like Console.Write()  WriteLine()  Like Console.WriteLine()  AutoFlush  Indicates whether to flush the internal buffer after each writing
  • 16. Writing to aText File – Example  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"); using (streamWriter) { for (int number = 1; number <= 20; number++) { streamWriter.WriteLine(number); } }
  • 19. What is Exception?  "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 was 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
  • 20. How to Handle Exceptions?  Using try{}, catch{} and finally{} blocks: try { // Some exception is thrown here } catch (<exception type>) { // Exception is handled here } finally { // The code here is always executed, no // matter if an exception has occurred or not }
  • 21. Catching Exceptions  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("somefile.txt"); Console.WriteLine("File successfully open."); } catch (FileNotFoundException) { Console.Error.WriteLine("Can not find 'somefile.txt'."); }
  • 22. Handling Exceptions When Opening a File try { StreamReader streamReader = new StreamReader( "c:NotExistingFileName.txt"); } catch (System.NullReferenceException exc) { Console.WriteLine(exc.Message); } catch (System.IO.FileNotFoundException exc) { Console.WriteLine( "File {0} is not found!", exc.FileName); } catch { Console.WriteLine("Fatal error occurred."); }
  • 25. Counting Word Occurrences – Example  Counting the number of occurrences of the word "foundme" in a text file: StreamReader streamReader = new StreamReader(@"....somefile.txt"); int count = 0; string text = streamReader.ReadToEnd(); int index = text.IndexOf("foundme", 0); while (index != -1) { count++; index = text.IndexOf("foundme", index + 1); } Console.WriteLine(count); What is missing in this code?
  • 27. Reading Subtitles – Example ..... {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:
  • 28. Fixing Subtitles – Example  Read subtitles file and fix it’s timing: static void Main() { try { // Obtaining the Cyrillic encoding System.Text.Encoding encodingCyr = System.Text.Encoding.GetEncoding(1251); // Create reader with the Cyrillic encoding StreamReader streamReader = new StreamReader("source.sub", encodingCyr); // Create writer with the Cyrillic encoding StreamWriter streamWriter = new StreamWriter("fixed.sub", false, encodingCyr); (example continues)
  • 29. Fixing Subtitles – Example try { string line; while ( (line = streamReader.ReadLine()) != null) { streamWriter.WriteLine(FixLine(line)); } } finally { streamReader.Close(); streamWriter.Close(); } } catch (System.Exception exc) { Console.WriteLine(exc.Message); } } FixLine(line) perform fixes on the time offsets: multiplication or/and addition with constant
  • 31. Summary  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  Exceptions are unusual events or error conditions  Can be handled by try-catch-finally blocks
  • 33. Exercises 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.
  • 34. Exercises (2) 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: 4 2 3 3 4 0 2 3 4 17 3 7 1 2 4 3 3 2
  • 35. Exercises (3) 6. 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 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).
  • 36. Exercises (4) 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, _. <?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>
  • 37. Exercises (5) 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.

Notas del editor

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  13. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  14. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  15. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  16. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  17. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  18. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*