SlideShare a Scribd company logo
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.

More Related Content

What's hot

Java I/O
Java I/OJava I/O
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
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
Anton Keks
 
Stream
StreamStream
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
Don Bosco BSIT
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
Arif Ullah
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
Docent Education
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
Io streams
Io streamsIo streams
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Basic of java
Basic of javaBasic of java
Basic of java
Kavitha713564
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
IO In Java
IO In JavaIO In Java
IO In Java
parag
 
File handling
File handlingFile handling
File handling
muhammad sharif bugti
 

What's hot (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
 

Viewers also liked

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
Diego Gutiérrez
 
Суфиксација
СуфиксацијаСуфиксација
Суфиксација
Aleksandra Džinić
 
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
 
HGFD
HGFDHGFD
HGFD
mobilefun
 
Presentation
PresentationPresentation
Presentation
VonNielsenR
 
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
Sam Bishop
 
Book Review - Learning Censorship
Book Review - Learning CensorshipBook Review - Learning Censorship
Book Review - Learning Censorship
Luke 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 Class
Sam Bishop
 
Bad Eggs 2 Cheats
Bad Eggs 2 CheatsBad Eggs 2 Cheats
Bad Eggs 2 Cheats
mobilefun
 
пейзажная лирика поэтов 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 Class
Sam 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 Class
Sam Bishop
 
power generation through speed breaker
power generation through speed breaker power generation through speed breaker
power generation through speed breaker
Ranjan Kumar Thakur
 

Viewers also liked (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 to 15. text files

Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
BG Java EE Course
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
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
ANUSUYA 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 java
JayasankarPR2
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
srgoc
srgocsrgoc
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
Akshay 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 5
Akshay 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/O
WebStackAcademy
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
ASP.NET Session 8
ASP.NET Session 8ASP.NET Session 8
ASP.NET Session 8
Sisir Ghosh
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 

Similar to 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
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.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
 

Recently uploaded

thrifthands-thrift store- get the latest trends
thrifthands-thrift store- get the latest trendsthrifthands-thrift store- get the latest trends
thrifthands-thrift store- get the latest trends
amarshifan555
 
MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024
MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024
MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024
DK PAGEANT
 
Insanony: Watch Instagram Stories Secretly - A Complete Guide
Insanony: Watch Instagram Stories Secretly - A Complete GuideInsanony: Watch Instagram Stories Secretly - A Complete Guide
Insanony: Watch Instagram Stories Secretly - A Complete Guide
Trending Blogers
 
一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理
一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理
一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理
lyurzi7r
 
Biography and career history of Bruno Amezcua
Biography and career history of Bruno AmezcuaBiography and career history of Bruno Amezcua
Biography and career history of Bruno Amezcua
Bruno Amezcua
 
The Fascinating World of Bats: Unveiling the Secrets of the Night
The Fascinating World of Bats: Unveiling the Secrets of the NightThe Fascinating World of Bats: Unveiling the Secrets of the Night
The Fascinating World of Bats: Unveiling the Secrets of the Night
thomasard1122
 
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANEMRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
DK PAGEANT
 
Self-Discipline: The Secret Weapon for Certain Victory
Self-Discipline: The Secret Weapon for Certain VictorySelf-Discipline: The Secret Weapon for Certain Victory
Self-Discipline: The Secret Weapon for Certain Victory
bluetroyvictorVinay
 
Capsule Wardrobe Women: A document show
Capsule Wardrobe Women:  A document showCapsule Wardrobe Women:  A document show
Capsule Wardrobe Women: A document show
mustaphaadeyemi08
 
Types of Garage Doors Explained: Energy Efficiency, Style, and More
Types of Garage Doors Explained: Energy Efficiency, Style, and MoreTypes of Garage Doors Explained: Energy Efficiency, Style, and More
Types of Garage Doors Explained: Energy Efficiency, Style, and More
Affordable Garage Door Repair
 
Analysis and Assessment of Gateway Process – HemiSync(1).PDF
Analysis and Assessment of Gateway Process – HemiSync(1).PDFAnalysis and Assessment of Gateway Process – HemiSync(1).PDF
Analysis and Assessment of Gateway Process – HemiSync(1).PDF
JoshuaDagama1
 

Recently uploaded (11)

thrifthands-thrift store- get the latest trends
thrifthands-thrift store- get the latest trendsthrifthands-thrift store- get the latest trends
thrifthands-thrift store- get the latest trends
 
MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024
MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024
MISS TEEN LUCKNOW 2024 - WINNER ASIYA 2024
 
Insanony: Watch Instagram Stories Secretly - A Complete Guide
Insanony: Watch Instagram Stories Secretly - A Complete GuideInsanony: Watch Instagram Stories Secretly - A Complete Guide
Insanony: Watch Instagram Stories Secretly - A Complete Guide
 
一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理
一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理
一比一原版(McGill毕业证书)麦吉尔大学毕业证如何办理
 
Biography and career history of Bruno Amezcua
Biography and career history of Bruno AmezcuaBiography and career history of Bruno Amezcua
Biography and career history of Bruno Amezcua
 
The Fascinating World of Bats: Unveiling the Secrets of the Night
The Fascinating World of Bats: Unveiling the Secrets of the NightThe Fascinating World of Bats: Unveiling the Secrets of the Night
The Fascinating World of Bats: Unveiling the Secrets of the Night
 
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANEMRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
MRS PUNE 2024 - WINNER AMRUTHAA UTTAM JAGDHANE
 
Self-Discipline: The Secret Weapon for Certain Victory
Self-Discipline: The Secret Weapon for Certain VictorySelf-Discipline: The Secret Weapon for Certain Victory
Self-Discipline: The Secret Weapon for Certain Victory
 
Capsule Wardrobe Women: A document show
Capsule Wardrobe Women:  A document showCapsule Wardrobe Women:  A document show
Capsule Wardrobe Women: A document show
 
Types of Garage Doors Explained: Energy Efficiency, Style, and More
Types of Garage Doors Explained: Energy Efficiency, Style, and MoreTypes of Garage Doors Explained: Energy Efficiency, Style, and More
Types of Garage Doors Explained: Energy Efficiency, Style, and More
 
Analysis and Assessment of Gateway Process – HemiSync(1).PDF
Analysis and Assessment of Gateway Process – HemiSync(1).PDFAnalysis and Assessment of Gateway Process – HemiSync(1).PDF
Analysis and Assessment of Gateway Process – HemiSync(1).PDF
 

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.

Editor's Notes

  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.*