Announcement:

This is just the beginning of this blog, please don't copy any of my posts.

Sunday, 23 December 2012

[Java] Implement a Program to Perform Various Operations on Text Files

Implement a program to accomplish the following task:
  • Create a text file and store data in it.
  • Count number of lines and words in the file.
  • Copy contents of one file to another file.

import java.io.*;
class Copycon
{
int count1,count,len;
void getdata()
{
try
{
RandomAccessFile ff=new RandomAccessFile ("student.dat","rw");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String choice=new String();
String s="";
int countc=count1=len=0;

do{
countc++;
count1++;
System.out.print("Enter the String :");
s=in.readLine();
ff.writeUTF(s);
len=s.length();
s=s.trim();

for(int i=0;i<len;i++)
{
if(s.charAt(i)==' ')
countc++;
}
System.out.print("Insert next line(Y/N):");
choice=in.readLine();
}
while(choice.compareTo("Y")==0||choice.compareTo("y")==0);
System.out.println("Number of Lines:"+count1);
System.out.println("Number of words:"+countc);
}
catch(Exception e)
{   }
}
public static void main(String args[])
{
Copycon c=new Copycon();
c.getdata();
File inFile=new File("input.txt");
File outFile=new File("output.txt");
FileReader ins=null;
FileWriter outs=null;
try
{
ins=new FileReader(inFile);
outs=new FileWriter(outFile);
int ch;
while((ch=ins.read())!=-1);
{
outs.write(ch);
}
}
catch(Exception e)
{
System.out.println(e);
System.out.println(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException e)
{}
}
Share it Please

Pankaj Gaikar

Pankaj Gaikar is a professional blogger from Pune, India who writes on Technology, Android, Gadgets, social media and latest tech updates at Punk Tech , Being Android & Shake The Tech . Email me HERE

0 comments :

Post a Comment

Copyright @ 2013 Pune University Bachelor of Engineering . Designed by Pankaj Gaikar | Love for The Tricks Machine