140 likes | 328 Views
Java . ashishfa. ? . How to read file in Java Developing application to expand abbreviation in given text “Mr. Vasant and Mr. Gajanan went to IIT” “Mister Vasant and Mister Gajanan went to Indian Institute of Technology”. Files for us.
E N D
Java ashishfa
? • How to read file in Java • Developing application to expand abbreviation in given text • “Mr. Vasant and Mr. Gajanan went to IIT” • “Mister Vasant and Mister Gajanan went to Indian Institute of Technology”
Files for us • Files can store text, formatted reports, pictures, songs, animations and programs • Names of files • report.doc • Readme.txt • Flower.jpg Text files means files that contain text (no other symbols.) i.e. the files that can be read through Notepad or editplus or vi in unix.
Files for computers • File has name in computer. • Java program cam read a file or write to a file or can modify the contents of file. • File is treated as a resource. • We need to open and close files while using them • To use files • It is assigned a name • It is then opened by open command • Then read /write commands are used • Then file is closed • File is treated as a resource.
code! FileReader fr = new FileReader("sample.txt"); BufferedReader bfr = new BufferedReader(fr); String str = bfr.readLine(); System.out.println("File contains"); while(str != null) { System.out.println(str); str = bfr.readLine(); } bfr.close();
Abbreviation expanding • Logic • Store abbreviations and corresponding expansions • Search them • Replace them • Repeat
data representation Ab. Expansion 0 Mr. Mister 1 Ms. Miss 2 Dr. Doctor 3 MA Master of arts
Find and replace • “Hello! Mr. Vasant” Mr. 0 0 2 7 10 16 1.>>Hello! << 2.>>Hello! Mister<< 3.>>Hello! Mister Vasant<<
String functions used a • indexof(String) • substring(a,b) • substring(a) • length() a b a end
See the code Abbr.java
Abbreviation expansion using file • Storing abbreviations in arrays in program is not convenient • Better way is to isolate data and program • i.e. keep abbreviations in seperate file • Read the abbreviations from this file • Modify abbreviation program
Abbreviation file Mr. Mister Dr. Doctor MA Master of arts . . . Odd line number 6 lines i.e. 3 entries Even line number 0 Mr. Mister 1 Dr. Doctor
exercise • Write a program to search a text file and print only those lines which has the search word in it. • Take i/p word from user • Open the text file • Read line by line from it • Search for i/p word in each line • Close file at the end
Thank You ;)