Question

In: Computer Science

- Create a java class named SaveFile in which write the following: Constructor: The class's constructor...

- Create a java class named SaveFile in which write the following:

Constructor: The class's constructor should take the name of a file as an argument

A method save (String line): This method should open the file defined by the constructor, save the string value of line at the end of the file, and then close the file.

- In the same package create a new Java class and it DisplayFile in which write the following:

Constructor: The class's constructor should take the name of a file as an argument

A method display(): This method should check if the file defined by the constructor  exist or not, if the file does not exist it displays the message "The file does not exists" and then exit the program, however if the file exists it displays the file contents line by line into the screen, and then close the file.

A method display (int n): This method is similar to display () but it displays the first n number of lines of the file's contents only. If the file contains less than n lines, it should display the file's entire contents.

A method display (int from, int to): This method is similar to display() but it displays the files's contents starting from line number from to the line number to. If the file contains less than to lines, it should display the file's contents. Note that, from is always less than to.

- In the same package, create another class called FilesDemo, in it's main method do the following:

create an instance of the class SaveFile to create new file named "lines.txt"

print the following lines into the file:

1-Lorem ipsum dolor sit amet

2-Consectetuer adipiscing elit

3-Sed diam nonummy nibh euismod tincidunt

4-Ut wisi enim ad minim veniam

5-Quis nostrud exerci tation ullamcorper

6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat

7-Duis autem vel eum iriure dolor in hendrerit

8-Vel illum dolore eu feugiat nulla facilisis at vero eros

Create an instance of the class DisplayFile to open "lines.txt"

using this instance invoke the method display()

using this instance invoke the method display(3) and display(10)

using this instance invoke the method display(3, 5)

Run your program and make sure it prints the correct output.

Solutions

Expert Solution

SaveFile.java

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class SaveFile {
private String fileName;
  
public SaveFile(String fileName)
{
this.fileName = fileName;
}
  
public void save(String line)
{
FileWriter fw;
PrintWriter pw;
try {
// open the file in append mode
fw = new FileWriter(new File(this.fileName), true);
pw = new PrintWriter(fw);
pw.write(line + System.lineSeparator());
  
pw.flush();
fw.close();
pw.close();
} catch (IOException ex) {
System.out.println("Error in writing to file: " + this.fileName);
System.exit(-1);
}
}
}

DisplayFile.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class DisplayFile {
private String fileName;
  
public DisplayFile(String fileName)
{
this.fileName = fileName;
}
  
public void display()
{
Scanner fileReader;
try
{
fileReader = new Scanner(new File(this.fileName));
System.out.println("FILE CONTENTS LINE-BY-LINE:");
while(fileReader.hasNextLine())
{
System.out.println(fileReader.nextLine().trim());
}
System.out.println();
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println("The file does not exist");
}
}
  
public void display(int n)
{
Scanner fileReader;
ArrayList<String> contents = new ArrayList<>();
try
{
fileReader = new Scanner(new File(this.fileName));
while(fileReader.hasNextLine())
{
contents.add(fileReader.nextLine().trim());
}
fileReader.close();
  
if(contents.size() < n)
{
System.out.println("ENTIRE FILE:");
for(String lines : contents)
{
System.out.println(lines);
}
System.out.println();
}
else
{
System.out.println("FIRST " + n + " LINES OF " + this.fileName + ":");
for(int i = 0; i < n; i++)
{
System.out.println(contents.get(i));
}
System.out.println();
}
}catch(FileNotFoundException fnfe){
System.out.println("The file does not exist");
}
}
  
public void display(int from, int to)
{
if(from > to)
System.out.println("From index should always be less than to index!\n");
else
{
Scanner fileReader;
ArrayList<String> contents = new ArrayList<>();
try
{
fileReader = new Scanner(new File(this.fileName));
while(fileReader.hasNextLine())
{
contents.add(fileReader.nextLine().trim());
}
fileReader.close();

if(contents.size() < to)
{
System.out.println("FILE CONTENTS FROM LINE " + from + ":");
for(int i = from; i < contents.size(); i++)
{
System.out.println(contents.get(i));
}
System.out.println();
}
else
{
System.out.println("FILE CONTENTS FROM LINE " + from + " TO " + to + ":");
for(int i = from; i <= to; i++)
{
System.out.println(contents.get(i - 1));
}
System.out.println();
}
}catch(FileNotFoundException fnfe){
System.out.println("The file does not exist");
}
}
}
}

FilesDemo.java

public class FilesDemo {
  
private static final String FILENAME = "lines.txt";
  
public static void main(String[] args)
{
SaveFile saveFile = new SaveFile(FILENAME);
saveFile.save("1-Lorem ipsum dolor sit amet");
saveFile.save("2-Consectetuer adipiscing elit");
saveFile.save("3-Sed diam nonummy nibh euismod tincidunt");
saveFile.save("4-Ut wisi enim ad minim veniam");
saveFile.save("5-Quis nostrud exerci tation ullamcorper");
saveFile.save("6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat");
saveFile.save("7-Duis autem vel eum iriure dolor in hendrerit");
saveFile.save("8-Vel illum dolore eu feugiat nulla facilisis at vero eros");
  
DisplayFile displayFile = new DisplayFile(FILENAME);
displayFile.display();
displayFile.display(3);
displayFile.display(10);
displayFile.display(3, 5);
}
}

**************************************************************** SCREENSHOT ***********************************************************

lines.txt

CONSOLE OUTPUT :

SaveFile.java x DisplayFile.java x L Files Demo.java x lines.txt X Source History B.Q O PBRO 1-Lorem ipsum dolor sit amet 2-consectetuer adipiscing elit. 3-Sed diam nonummy nibh euismod tincidunt. 4-Ut wisi enim ad minim veniam 5-Quis nostrud exerci tation ullamcorpe. 6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat 7-Duis autem vel eum iriure dolor in hendrerit 8-Vel illum dolore eu feugiat nulla facilisis at vero eros

run: FILE CONTENTS LINE-BY-LINE: 1-Lorem ipsum dolor sit amet 2-Consectetuer adipiscing elit 3-Sed diam nonummy nibh euismod tincidunt 4-Ut wisi enim ad minim veniam 5-Quis nostrud exerci tation ullamcorper 6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat 7-Duis autem vel eum iriure dolor in hendrerit 8-Vel illum dolore eu feugiat nulla facilisis at vero eros FIRST 3 LINES OF lines.txt: 1-Lorem ipsum dolor sit amet 2-Consectetuer adipiscing elit 3-Sed diam nonummy nibh euismod tincidunt ENTIRE FILE: 1-Lorem ipsum dolor sit amet 2-Consectetuer adipiscing elit 3-Sed diam nonummy nibh euismod tincidunt 4-Ut wisi enim ad minim veniam 5-Quis nostrud exerci tation ullamcorper 6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat 7-Duis autem vel eum iriure dolor in hendrerit 8-Vel illum dolore eu feugiat nulla facilisis at vero eros FILE CONTENTS FROM LINE 3 TO 5: 4-Ut wisi enim ad minim veniam 5-Quis nostrud exerci tation ullamcorper 6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat BUILD SUCCESSFUL (total time: 0 seconds)


Related Solutions

Lab to be performed in Java. Lab: 1.) Write a class named TestScores. The class constructor...
Lab to be performed in Java. Lab: 1.) Write a class named TestScores. The class constructor should accept an array of test scores as its argument. The class should have a method that returns the average of the test scores. If any test score in the array is negative or greater than 100, the class should throw an IllegalArgumentException. Write a driver class to test that demonstrates that an exception happens for these scenarios 2.) Write a class named InvalidTestScore...
Java program Create a constructor for a class named Signal that will hold digitized acceleration data....
Java program Create a constructor for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp data The constructor...
In java: -Create a class named Animal
In java: -Create a class named Animal
write program in java Create a class named PersonalDetails with the fields name and address. The...
write program in java Create a class named PersonalDetails with the fields name and address. The class should have a parameterized constructor and get method for each field.  Create a class named Student with the fields ID, PersonalDetails object, major and GPA. The class should have a parameterized constructor and get method for each field. Create an application/class named StudentApp that declare Student object. Prompts (GUI input) the user for student details including ID, name, address, major and GPA....
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of the account holder. a method, getBalance, that returns a double corresponding to the account balance. a method withdraw that accepts a double, and deducts the amount from the account balance. Write a class definition for a subclass, CheckingAccount, that contains: a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance). a constructor that...
In C++ Write a class named TestScores. The class constructor should accept an array of test...
In C++ Write a class named TestScores. The class constructor should accept an array of test scores as its argument. The class should have a member function that returns the average of the test scores. If any test score in the array is negative or greater than 100, the class should throw an exception. Demonstrate the class in program.
THIS IS JAVA PROGRAMMING 1. Create a class named Name that contains the following: • A...
THIS IS JAVA PROGRAMMING 1. Create a class named Name that contains the following: • A private String to represent the first name. • A private String to represent the last name. • A public constructor that accepts two values and assigns them to the above properties. • Public methods named getProperty (e.g. getFirstName) to return the value of the property. • Public methods named setProperty ( e.g. setFirstName)to assign values to each property by using a single argument passed...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class named Book. In the Book class: Add the following private instance variables: title (String) author (String) rating (int) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. Add a second constructor that receives only 2 String parameters, inTitle and inAuthor. This constructor should only assign input parameter values to title and...
Create a Java project called Lab3A and a class named Lab3A. Create a second new class...
Create a Java project called Lab3A and a class named Lab3A. Create a second new class named Employee. In the Employee class: Add the following private instance variables: name (String) job (String) salary (double) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. (Refer to the Tutorial3 program constructor if needed to remember how to do this.) Add a public String method named getName (no parameter) that...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT