Write a class called FileOperations that accepts a string va

Write a class called FileOperations that accepts a string value in a variable called str which represents the name of a text file residing on an external storage device. Provide the following:

(a)     A constructor that accepts the string str, representing the file name, and creates a LineNumberReader object.                                                                                     [ 1 mark]

(b)    A mutator method that reads the file line by line until the file is empty.                  [ 2 marks]

(c)     An accessor method that determines if the actual file exists.                                  [ 1 mark]

(d)    An accessor method that returns the number of bytes in the file.                          [ 1mark]

(e)     An accessor method that returns the name of the file.                                          [ 1 mark]

(f)      The declaration of appropriate variables and use of Exception where necessary.    [ 2 marks]

Note :– a test class is NOT required

Solution

Please find the required solution:(As required test class is not provided)

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/**
* FileOperations class
*/
public class FileOperations {

LineNumberReader obj;
String content;
File file;

/**
* a.Accepts string file name as input and create LineNumberReader object
*
* @param str
* input file name
* @throws FileNotFoundException
*/
FileOperations( String str ) throws FileNotFoundException
{
file = new File(str);
if( fileExists(file) )
obj = new LineNumberReader(new FileReader(file));
}

/**
* b. A mutator method that reads the file line by line until the file is empty.
*
* @throws IOException
*/

public void getContent() throws IOException
{
StringBuilder builder = new StringBuilder();
while( obj.read() != -1 )
{
builder.append(obj.readLine());
}
content = builder.toString();
}

/**
* c.
*
* @param file
* existence true if exists else false
* @return
*/
public boolean fileExists( File file )
{
return file.exists();
}

/**
* d.
*
* @return file length
*/
public long fileLength()
{
return file.length();
}

/**
* e.
*
* @returns the name of file
*/
public String filename()
{
return file.getName();
}
}

 Write a class called FileOperations that accepts a string value in a variable called str which represents the name of a text file residing on an external stora
 Write a class called FileOperations that accepts a string value in a variable called str which represents the name of a text file residing on an external stora

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site