This document discusses reading from and writing to files in Java programs. It explains how to open a file using a Scanner or PrintWriter object, read/write data using methods like next() and println(), and close the file when finished. It recommends storing file data in memory structures, processing it, then writing the results back to improve efficiency over sequential file access. Proper file handling and exception handling are also emphasized.
File Handling is used in C language for store a data permanently in computer.
Using file handling you can store your data in Hard disk.
http://www.tutorial4us.com/cprogramming/c-file-handling
File Handling is used in C language for store a data permanently in computer.
Using file handling you can store your data in Hard disk.
http://www.tutorial4us.com/cprogramming/c-file-handling
Selection Statements
Using if and if...else
Nested if Statements
Using switch Statements
Conditional Operator
Repetition Statements
Looping: while, do, and for
Nested loops
Using break and continue
Selection Statements
Using if and if...else
Nested if Statements
Using switch Statements
Conditional Operator
Repetition Statements
Looping: while, do, and for
Nested loops
Using break and continue
File Handling Btech computer science and engineering pptpinuadarsh04
Data is very important. Every organization depends on its data for continuing its business operations. If the data is lost, the organization has to be closed. To store data in a computer, we need files. For example, we can store employee data like employee number, name and salary in a file in the computer and later use it whenever we want.
Similarly, we can store student data like student roll number, name and marks in the computer. In computers’ view, a file is nothing but collection of data that is available to a program. Once we store data in a computer file, we can retrieve it and use it depending on our requirements.
This is the reason computers are primarily created for handling data, especially for storing and retrieving data. In later days, programs are developed to process the data that is stored in the computer.
Assets, Files, and Data Parsing
Android offers a few structured ways to store data, notably SharedPreferences and local SQLite databases.
And, of course, you are welcome to store your data “in the cloud” by using an Internet-based service.
Beyond that, though, Android allows you to work with plain old ordinary files, either one baked into your app (“assets”) or ones on so-called internal or external storage.
To make those files work — and to consume data off of the Internet — you will likely need to employ a parser. Android ships with several choices for XML and JSON parsing, in addition to third-party libraries you can attempt to use.
This session focuses on Assets, Raw, and Files.
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
http://youtu.be/YD5Yk6cNsdE
1. File Handling
OOSSE - Programming with Java
Lecture A1
Dec 21, 2012 OOSSE - Java Lecture A1 1
2. Objectives
In this lecture, we will:
– learn how to read data from a file
– learn how to write data to a file
– discuss the structure of a program which uses files
Dec 21, 2012 OOSSE - Java Lecture A1 2
3. Why use files?
• In all the programs we have written so far, any data we
need has been either
– hard coded into the program
String name = "Cathy";
– or read in from the keyboard using a Scanner object
Scanner kybd = new Scanner(System.in);
System.out.println("What is your name?");
name = kybd.next();
• It is tedious to type in all the data to be processed each time
the program is run
• It is not very useful if the data and results cannot be saved
– imagine a payroll program where all information about the
employees has to be entered each time the program is run
Dec 21, 2012 OOSSE - Java Lecture A1 3
4. Opening a file to read from
• A Scanner object can be set up to read from a file
– so far all our Scanner objects have read from the keyboard
• The name of the file to read from is required
• First create a File object corresponding to this file
– need to import java.io.*
– this is a library of java classes for input and output
• Then create a Scanner object using the File object as the
source of the input
– instead of System.in
• If the input file is in the same directory as the Java program it
makes life easier
– if the file is not found, there will be an error (exception) when the
program runs
Dec 21, 2012 OOSSE - Java Lecture A1 4
5. Reading from a file
import java.util.*;
import java.io.*;
public class Payroll
{
public static void main(String args[])
{
String fName = "payroll.txt";
Scanner inFile = new Scanner(new File(fName));
……
or
Scanner inFile =
new Scanner(new File("payroll.txt"));
Dec 21, 2012 OOSSE - Java Lecture A1 5
6. Reading from Scanner objects
• Once the Scanner object is created, we can use its
methods to read from the file
– just like when reading from the keyboard
String name = inFile.next();
double hourlyPay = inFile.nextDouble();
• Multiple Scanner objects can be created, as long as they
are given different names
– for example, to read from two different files
– or from a file and the keyboard
Scanner kybd = new Scanner(System.in);
Scanner inFile = new Scanner(new File(fName));
Dec 21, 2012 OOSSE - Java Lecture A1 6
7. Reading from a file
• The hasNext() method is useful when you do not know how
much data is in the file
– returns true if there is more data to read
– returns false if you have reached the end of the file
• It can be used in a while loop to process all the data in the file
• Imagine a text file is available where each line contains
information about one employee:
– name (as a String)
– followed by hourly pay (as a double)
• For example the file could contain the data
Nick 4.95
Fred 5.94
Dave 9.45
• The code overleaf would process all the data in turn
Dec 21, 2012 OOSSE - Java Lecture A1 7
8. Reading all the data in a file
while (inFile.hasNext())
{
name = inFile.next();
hourlyPay = inFile.nextDouble();
System.out.println("Hours worked by "+name+"?");
hoursWorked = kybd.nextInt();
double pay = hourlyPay * hoursWorked;
System.out.println("Pay is " + pay);
}
inFile.close();
Dec 21, 2012 OOSSE - Java Lecture A1 8
9. Closing a file
• When you have finished reading from a file, you should
close it
• A file is closed by calling the close() method of the
Scanner object that was set up to read the file
inFile.close();
Dec 21, 2012 OOSSE - Java Lecture A1 9
10. Tips for Input Files
• Decide on the format of the data
– repeating rows of
• name (as a String)
• followed by hourly pay (as a double)
• Make sure the information is
– in the correct order
– of the correct type
• to match the input statements in your program
• Any text editor can be used to create and edit the file
• or it could be output from a program
– which writes to the file using the correct format
Dec 21, 2012 OOSSE - Java Lecture A1 10
11. Writing to a file
• The name of the file to write to is required
• First create a PrintWriter object for this file
– need to import java.io.*
– same library of java classes as FileReader
• Typically the output file will be in the same directory as the Java
program
• If a file of this name already exists
– it will be opened
– all the data currently in the file will be lost
• If the file does not already exist, a new one will be created
PrintWriter pw = new PrintWriter("Payroll.txt");
Dec 21, 2012 OOSSE - Java Lecture A1 11
12. Writing to a file
• Once the PrintWriter object is created, we can use its
methods to write to the file
– can use print(), println(), printf()
– just like when writing to the console output window
• For example to print an employee’s data on one line
pw.print(name);
pw.printf("%6.2f", hourlyPay);
pw.println();
• Close the PrintWriter when you have finished writing to
the file
pw.close();
Dec 21, 2012 OOSSE - Java Lecture A1 12
13. Structure of a program that uses files
• A program which reads data from a file may do a lot of
processing on it
– do calculations (totals, averages)
– add to it (input by user)
– delete some of it
– sort it
– search all of it for a particular data value
• It is awkward to search for and retrieve only the required
data from a sequential file for each process
• and to write changes back to the original file
Dec 21, 2012 OOSSE - Java Lecture A1 13
14. Structure of a program that uses files
• It is sometimes better to
– open the input file
– read all the data in the file into an appropriate data structure
• such as an array, or several arrays
– close the input file
• Do all the processing in memory, then write the final version
of the data to a file
– either with the same name as the input file
• original data is lost
– or a new file
• Most of the program (data structures, processing) is the
same as when all the data is entered via the keyboard
– just add the file-reading code at the beginning of the program
– and the file-writing code at the end
Dec 21, 2012 OOSSE - Java Lecture A1 14
15. Files and Exceptions
• File handling is one area that is prone to things going
wrong
– A file may not exist
– A file may not be accessible
– The format of the data in the file may be incorrect
• Whenever dealing with files it is best to make use of try
catch blocks to handle any exceptions
– Try to anticipate what could go wrong
Dec 21, 2012 OOSSE - Java Lecture A1 15
16. Summary
In this lecture we have:
• learned how to read data from a file
• learned how to write data to a file
• discussed the structure of a program which uses files
Dec 21, 2012 OOSSE - Java Lecture A1 16
Editor's Notes
Part of this lecture will be reserved for working through solutions to selected exercises from last week. Notes relating to this do not appear in the slides.