Header Ads Widget

Ticker

6/recent/ticker-posts

Practical 10 Java

File Handling Using Java:
1. Write a programme to count occurrence of a given words in a file.

package com.company;
import java.io.BufferedReader; import java.io.FileReader; public class Main {
public static void main(String[] args) { try {
String line; int count = 0;
String search = "vedant";
FileReader file = new FileReader("C:\\Users\\HP\\Desktop\\vedant.txt"); BufferedReader br = new BufferedReader(file);
while ((line = br.readLine()) != null) { String words[] = line.split(" ");
for (String word : words) { if (word.equals(search))
count++;
}
}
System.out.println("Number of occurrence of words \"" + search + "\" present in given file: " + count);
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}


2. Write a program to print it seltf.

package com.company;
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader;

public class Main {
public static void main(String[] args) {
{
try {
FileInputStream fstream = new FileInputStream("C:\\Users\\HP\\IdeaProjects\\evenoddbythreads\\src\\com\\company\\Main
.java");//here pass the own java file name with full path

BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String s;
while ((s = br.readLine()) != null) { System.out.println(s);
}
br.close();
} catch (Exception e) { e.printStackTrace();
}

}
}
}


3. Write a program to display list of all the files of given directory

package com.company; import java.io.File;
import java.io.IOException;

public class Main
{
public static void main(String[] args)
{
File currentDir = new File("C:\\Users\\HP\\IdeaProjects"); displayDirectory(currentDir);
}
public static void displayDirectory(File dir)
{
try {
File[] files = dir.listFiles(); for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:"+ file.getCanonicalPath()); displayDirectory(file);
}
else {
System.out.println("file:"+ file.getCanonicalPath());
}
}
}
catch (IOException e) { e.printStackTrace();
}
}
}

Post a Comment

0 Comments