JAVA: File Handling
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.
File Handling
The File class from the java.io package.
To use the File class, create an object of the class, and specify the filename or directory name:
import java.io.File; // Import the File class
File myObj = new File(“filename.txt”); // Specify the filename
Operations
· canRead
· canWrite
· createNewFile
· delete
· exists
· getName
· getAbsolutePath
· length
· list
· mkdir
Example
package ninteen;
import java.util.*;
import java.io.*;
public class assesment02
{
public static void main(String args[])throws Exception
{
String data1 = “HAPPY NEW YEAR”;
try {
FileOutputStream file = new FileOutputStream(“data.txt”);
byte b[] = data1.getBytes();
file.write(b);
file.close();
System.out.println(“File created successfully”);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
System.out.println(e);
}
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
map.put(‘A’,0);
map.put(‘E’,0);
map.put(‘I’,0);
map.put(‘O’,0);
map.put(‘U’,0);
try {
FileInputStream file = new FileInputStream(“data.txt”);
String data = “”;
int i = 0;
while ((i = file.read()) != -1)
{
if ((char) i == ‘A’){
map.put(‘A’,map.get(‘A’)+1) ;
}
if ((char) i == ‘E’){
map.put(‘E’,map.get(‘E’)+1) ;
}
if ((char) i == ‘I’){
map.put(‘I’,map.get(‘I’)+1) ;
}
if ((char) i == ‘O’){
map.put(‘O’,map.get(‘O’)+1) ;
}
if ((char) i == ‘U’){
map.put(‘U’,map.get(‘U’)+1) ;
}
}
System.out.println(“Count of A is “+map.get(‘A’));
System.out.println(“Count of E is “+map.get(‘E’));
System.out.println(“Count of I is “+map.get(‘I’));
System.out.println(“Count of O is “+map.get(‘O’));
System.out.println(“Count of U is “+map.get(‘U’));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}