CMP201 File Handling
CMP201 File Handling
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,
• 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
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.");
}
}