Java Assignment 4
Java Assignment 4
Q.1. Write a Java program to copy a file into another file and delete
first file.
Ans.:
import java.io.*;
class FileDel
for(int i=0;i<args.length;i++)
if(file.isFile())
String name=file.getName();
if(name.endsWith(".txt"))
file.delete();
System.out.println("file is deleted "+file);
else
{System.out.println(name+" "+file.length()+"
bytes");}
else
Ans.:
Syntax:
o try
o {
o // block of code to monitor for errors
o }
o catch (ExceptionType1 exOb)
o {
o // exception handler for ExceptionType1
o }
o catch (ExceptionType2 exOb)
o {
o // exception handler for ExceptionType2
o }
o // ...
o finally
o {
o // block of code to be executed before try block ends
o }
Ans.:
import java.util.*;
public class InputChecker
{
public static void main(String[ ] args)
{
System.out.print("Enter data - ");
char data = new Scanner(System.in).next( ).charAt(0);
if (Character.isLetter(data))
System.out.println("It is in "+ (Character.isLowerCase(data) ?
"Lowercase" : "Uppercase"));
else if (Character.isDigit(data))
try
{
throw new DigitNotAllowed( );
}
catch (DigitNotAllowed e)
{
System.out.println("Digit not allowed!");
}
}
}
Q.4. Write a Java program to copy alternate word from file into
another file.
Ans.:
import java.io.*;
class CopyAlternateWord
String str;
int i,cnt;
while((i=fr.read())!=-1)
str+=(char)i;
}
cnt=0;
if(str[j]==” ”)
cnt++;
else if(cnt%2!=0)
continue;
else
fw.write(str[j]);
fr.close();
fw.close();
}
Q.5. Write a java program to count occurrence of ‘is’ word in the file .
Ans.:
import java.io.*;
class GFG
{
public static void main(String args[])
{
FileInputStream f=new FileInputStream("Cfile.txt");
char ch;
int n=f.available();
String word = "is";
int count = 0;
if (word.equals(ch))
count++;
}
Ans.:
import java.util.*;
import java.io.*;
class Cfile
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;
}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n);
}
}