0% found this document useful (0 votes)
12 views21 pages

CMP201 File Handling

Uploaded by

abdurafiuadam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

CMP201 File Handling

Uploaded by

abdurafiuadam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

CMP 201: File Handling in Java

The Concept of File


• Files are the most important mechanism for storing data
permanently on mass-storage devices.
• Permanently means that the data is not lost when the
machine is switched off as opposed to “primary” storage in
memory
• Stores a sequence of bytes/characters
• Each file is associated with a filename
• Often organized under a directory hierarchy
• A directory is a location in which the file is placed (one may
consider the whole path that allows one to find the file on
the hard-disk as part of the name of the file).
File Types
• Binary File: Stores data in a format that can be interpreted
by programs, but not easily by humans.
• Text File: Stores alphanumeric characters, codified in a
standard way (e.g., using ASCII or Unicode), and directly
readable by a human user.
• Text files are normally organized in a sequence of lines, each
containing a sequence of characters and ending with a special
character (usually the newline character).
• Consider, for example, a Java program stored in a file on the
hard-disk.
• In this course we will deal only with text files
Binary Vs Text Files

• Text files: the bits represent printable characters


• One byte per character for ASCII, the most common code
• Binary files: the bits represent other types of encoded
information, such as executable instructions or numeric
data
• These files are easily read by the computer but not humans
• They are not "printable" files
• Actually, you can print them, but they will be unintelligible
• "printable" means "easily readable by humans when printed"
File Operations in Java

• What can you do with a file in Java?


• Creating a file
• Writing data to a file
• Reading data from a file
• Deleting a file
• Getting information of a file
File Operations in Java
• To execute reading and writing operations on a file, we must open the file
before doing the operations, and close it after we finished operating on it.
• Opening a file means to indicate to the operating system that we want to
operate on a file from within a Java program, and the operating system
verifies whether such operations are possible and allowed.
• There are two ways of opening a file:
• Opening for reading
• and opening for writing
• In many programming languages (including Java), opening a file for writing
means actually to create a new file.
• Closing a file means to indicate to the operating system that the file that was
previously opened is not being used anymore by the program.
• Closing a file also has the effect of ensuring that the data written on the file are
effectively transferred to the hard-disk.
Reading and Writing Files
• Java uses Streams to perform input-output (I/O) operations on a
file.
• A stream is an object that either delivers data to its destination
(screen, file, etc.) or that takes data from a source (keyboard,
file, etc.)
• A stream acts as a buffer between the data source and destination
that connects program to I/O object.
• Input stream: a stream that provides input to a program. The
input stream reads or retrieves data from a source. For example,
System.in is an input stream which connect program to the
keyboard.
• Output stream: a stream that accepts output from a program. The
output stream writes data to a destination. For example,
System.out is an output stream which connects program to the
screen.
keyboard
standard
input stream
CPU
standard
output MEM
monitor stream
terminal
console

HDD
What does information
travel across?
Streams
keyboard
standard
input stream
CPU
standard
output MEM
monitor stream
terminal file
console input
stream
LOAD HDD
What does information READ
travel across? file
files output
Streams
stream
SAVE
Reading and Writing Files
• The File class from the java.io package, allows us to work
with files.
• To use the File class, create an object of the class, and
specify the filename or directory name.
• For Example,

• Java File class represents the files and directory pathnames


in an abstract manner.
• This class is used for creation of files and directories, file
searching, file deletion, etc.
• The File object represents the actual file/directory on the
disk.
File Class Methods
Review Scanner
• Simplest way to understand this concept is to extend our use of
Scanner
• Associate with files instead of System.in
• All input classes, except Scanner, are in java.io
• import java.io.*;
• We’ve used Scanner before
• The constructor takes an object of type java.io.InputStream –
stores information about the connection between an input
device and the computer or program
• Example: System.in

• Recall – only associate one instance of Scanner with


System.in in your program
• Otherwise, get bugs
Numerical Input
• 2 ways (we’ve learned one, seen the other)
• Use int as example, similar for double
• First way:
• Use nextInt()
• int number = scanner.nextInt();

• Second way:
• Use nextLine(), Integer.parseInt()
• String input = scanner.nextLine();
• int number = Integer.parseInt(input);

• Optimal use
• nextInt() when there is multiple information on one line
• nextLine() + parseInt() when one number per line
Important Sequence

• To write to a text file • To read from a text


1. Create it. file
2. Write to it 1. Open it.
(repeatedly). 2. Read from it
3. Flush it (optional) (repeatedly).

4. Close it. 3. Close it


• Assumes the file
exists.
Writing to Text Files
• Create the text file
• PrintWriter f = new PrintWriter( “filename.txt” ); Or
• FileWriter f=new FileWriter(“filename.txt");
• This opens the file.
• File is initially empty.
• Write to the text file
• f.println(…); // use like System.out Or
• f.write(…);
• Can be repeated.
• Close the file before exiting the program
• f.close(); // ensures contents are updated
• If you want to update the file without closing it yet, you can call
f.flush();
Reading from a Text File

• Open the text file


• FileReader reader = new FileReader( “file.txt”)
• Scanner in = new Scanner( reader )
• Read from the text file
• String line = in.nextLine();
• Can be repeated.
• Close the text file
• in.close();
Example Program – Creating a File
import java.io.*;
public class FileHandle{
public static void main(String []arr) throws IOException{
// an object of file class
File f=new File("C:/Users/aidri/Desktop/demo.txt");
// creating a new file
Boolean result=f.createNewFile();
if(result)
System.out.print(f+" created successfully.");
else
System.out.format("%s","File cannot be created due to some error.");
}
}
Example Program – Getting File Information
import java.io.*;
public class FileHandle{
public static void main(String []arr) throws IOException{
File file=new File("demo.txt");
file.createNewFile();
String filename=file.getName();
System.out.println("File Name is "+filename);
System.out.println("Absolute path of "+filename+" : "+file.getAbsolutePath());
System.out.print("length of "+filename+" : "+file.length());
System.out.println("Is "+filename+" readable? "+file.canRead());
System.out.println("Is "+filename+" writable? "+file.canWrite());
System.out.println("Is "+filename+" exists? "+file.exists());
}
}
Example Program – Writing Data to a File

import java.io.*;
public class FileHandle{
public static void main(String []arr) throws IOException{
// creating a new file and writing data to a file
FileWriter fw=new FileWriter("demo.txt");
String s="Welcome, this is tutorial of Java File Handling in Java.";
fw.write(s);
// closing a file
fw.close();
}
}
Example Program – Reading Data from a File
import java.io.*;
import java.util.Scanner;
public class FileHandle{
public static void main(String []arr) throws IOException{
File f=new File("demo.txt");
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
String str=sc.nextLine();
System.out.println(str);
}
// closing a file
sc.close();
}
}
Example Program – Deleting a File

import java.io.*;
public class FileHandle{
public static void main(String []arr) throws IOException{
File f=new File("demo.txt");
Boolean result=f.delete();
if(result)
System.out.print(f+" deleted successfully.");
else
System.out.format("%s","File cannot be deleted due to some error.");
}
}

You might also like