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

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Input and Output Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
Tim Wentz Nathaniel Smith Andrew Johnson. Files in Java Create a new file handle using: ▫new File(String pathname); Pathnames can be either relative or.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Chapter 9: Sequential Access Files and Printing
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
1 CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
15-Jul-15 Simple Java I/O Part I General Principles.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Computer and Programming File I/O File Input/Output Author: Chaiporn Jaikaeo, Jittat Fakcharoenphol Edited by Supaporn Erjongmanee Lecture 13.
C# B 1 CSC 298 Writing a C# application. C# B 2 A first C# application // Display Hello, world on the screen public class HelloWorld { public static void.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Files and Streams File Types, Using Streams, Manipulating Files SoftUni Team Technical Trainers Software University
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Tutorial 9: Sequential Access Files and Printing1 Tutorial 9 Sequential Access Files and Printing.
File Input and Output (I/O) Engineering 1D04, Teaching Session 7.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Ten Structures and Sequential Access Files.
CSC 298 Streams and files.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
File Input and Output Chapter 14 Java Certification by:Brian Spinnato.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
File Output Writing data out to a file 1. Output to files  StreamWriter : An object in the System.IO namespace that lets you print output to a destination.
Streams, File I/O and Scanner class
OO Design and Programming II I/O: Reading and Writing
Basic Text File Input/Output
Text File Input/Output
Text File Input/Output
I/O Basics.
File Types, Using Streams, Manipulating Files
Part I General Principles
Files and Streams.
Sequential Input and Output using Text Files
File Input/Output (I/O)
CSS 161: Fundamentals of Computing
Files & Streams.
Tutorial 9 Sequential Access Files and Printing
CIS16 Application Development and Programming using Visual Basic.net
BO65: PROGRAMMING WRITING TO TEXT FILES.
File Input and Output.
Files and Streams.
Presentation transcript:

Reading and Writing Text Files Svetlin Nakov Telerik Corporation

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

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

 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

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

 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: 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")); "cyr.txt", Encoding.GetEncoding("windows-1251")); // Read the file contents here... reader.Close();

 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}

 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(); }}

Live Demo

Using 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")); false, Encoding.GetEncoding("windows-1251")); StreamWriter streamWriter = new StreamWriter("test.txt");

 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

 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); }}

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

 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 }

 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"); StreamReader reader = new StreamReader("somefile.txt"); Console.WriteLine("File successfully open."); Console.WriteLine("File successfully open.");} catch (FileNotFoundException) { Console.Error.WriteLine("Can not find 'somefile.txt'."); Console.Error.WriteLine("Can not find 'somefile.txt'.");}

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.");}

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?

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:

 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)

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

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  Exceptions are unusual events or error conditions  Can be handled by try-catch-finally blocks

Questions?

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.

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

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

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.