Question

In: Computer Science

Using a minimum of 2 classes create a java program that writes data to a file...

Using a minimum of 2 classes create a java program that writes data to a file when stopped and reads data from a file when started. The data should be in a readable format and the program should work in a way that stopping and starting is irrelevant (e.g. all data doesn't have to save just the important elements.) Program should be unique and semi-complex in some way.

Solutions

Expert Solution

I have used FileReader and BufferedWriter to successfully read and write in append mode to the file. Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. It is character-oriented class which is used for file handling in java.

I have created two classes namely, fileIO and fileHandling. In fileIO class, I have defined two functions. One functions is used here to open the file in append mode and write the user declared string to the file. Other function is used here to open the file in read mode and print whatever content is written in it. In fileHandling class, I have prompted the user to write to file, read from file, exit the program. As soon the user enters the option, their respective switch case block is executed and functions created in fileIO are called from there.

Here is the code for the same:-

import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.util.*;

class fileIO{
    public void WriteToFile(String fname,String str) throws IOException{
         try {

            // Open given file in append mode.
            BufferedWriter out = new BufferedWriter(new FileWriter(fname, true));

            out.write(str); //Write to the file
            out.close();    //Closing the file
            System.out.println("Writing successful...");    //Print Acknowledgement
        }
        catch (IOException e) {
            System.out.println("exception occoured" + e); //In case error occured
        }
    }

    public void ReadFromFile(String fileName) throws IOException{
        // variable declaration
        int ch;

        // check if File exists or not
        FileReader fr=null;
        try
        {
            fr = new FileReader(fileName);
        }
        catch (FileNotFoundException fe)
        {
            System.out.println("File not found!"); //in case exception occur
        }

        System.out.print("");   //for Proper Output Formatting
        // read from FileReader till the end of file
        while ((ch=fr.read())!=-1)
            System.out.print((char)ch);

        // close the file
        fr.close();
        System.out.println(""); //for Proper Output Formatting
        System.out.println(""); //for Proper Output Formatting
    }
}


class fileHandling{
    public static void main(String args[])throws IOException{

        char ch='y';   
        int choice;   //For taking input choice from user
        Scanner scr=new Scanner(System.in);     //Scanner object to take input
        fileIO f1 = new fileIO();         //Creating an object of fileIO class to call its functions
        do{
            System.out.println("*** File Handling ***");
            System.out.println("1. Wrtite to File");
            System.out.println("2. Read from File");
            System.out.println("3. Exit the Program");
            System.out.println("Enter Your Choice...");

            //nextLine() to read next line from the user

            choice=Integer.parseInt(scr.nextLine());    //parseInt() is use to convert string to integer
            switch(choice){
                case 1:
                        System.out.println("Enter File Name : ");
                        String file;
                        file=scr.nextLine();     //reading File name from the user
                        System.out.println("Enter string to be written : ");
                        String str;
                        str=scr.nextLine();     //read String to be written in the file
                        f1.WriteToFile(file,str); //Calling function to write in the file
                        System.out.println("");
                        break;
                case 2:
                        System.out.println("Enter File Name : ");
                        String file1;
                        file1=scr.nextLine();   //taking the input of file name to be opened in Read mode
                        f1.ReadFromFile(file1); //Calling the function to read from the file
                        break;
                case 3:
                        System.out.println("Exiting the Program");   //Exiting the program
                        return; //main ends if case 3 runs
                default:
                        System.out.println("Wrong Choice! Try Again...");
                        System.out.println(""); //for Proper Output Formatting
            }
        }while(ch=='y');

        scr.close();
    }        //main ends here
}    //fileHandling ends here

The sample output for the same is:-

Hope this helps you. Feel free to ask queries in the comment section.

Happy Learning...


Related Solutions

Create a moderately complex java program that utilises 2 or more classes. Within these classes: -...
Create a moderately complex java program that utilises 2 or more classes. Within these classes: - have one that defines an exception - have that exception throw(n) in one method and handled in another -has the program continue even if the user inputs incorrect data -be creative/unique in some way
In JAVA Write a brief program that writes your name to a file in text format...
In JAVA Write a brief program that writes your name to a file in text format and then reads it back. Use the PrintWriter and Scanner classes.
In Java language. Write a brief program that writes your name to a file in text...
In Java language. Write a brief program that writes your name to a file in text format and then reads it back. Use the PrintWriter and Scanner classes.
2. Create a java program that reads a file line by line and extract the first...
2. Create a java program that reads a file line by line and extract the first word.        The program will ask for the name of input and output file. Input file: words.txt today tomorrow sam peterson peter small roy pratt Output file: outwords.txt tomorrow peterson small pratt
Write a java program that can create, read, and append a file. Assume that all data...
Write a java program that can create, read, and append a file. Assume that all data written to the file are string type. One driver class and a class that contains the methods. The program should have three methods as follows: CreateFile - only creating a file. Once it create a file successfully, it notifies to the user that it creates a file successfully. ReadingFile - It reads a contents of the file. This method only allow to read a...
Answer the following in Java programming language Create a Java Program that will import a file...
Answer the following in Java programming language Create a Java Program that will import a file of contacts (contacts.txt) into a database (Just their first name and 10-digit phone number). The database should use the following class to represent each entry: public class contact {    String firstName;    String phoneNum; } Furthermore, your program should have two classes. (1) DatabaseDirectory.java:    This class should declare ArrayList as a private datafield to store objects into the database (theDatabase) with the...
Create a Java program that asks a user to enter two file names. The program will...
Create a Java program that asks a user to enter two file names. The program will read in two files and do a matrix multiplication. Check to make sure the files exist. first input is the name of the first file and it has 2 (length) 4 5 6 7 Second input is the name of the second file and it has 2 (length) 6 7 8 9 try catch method
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type...
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type int and outputs all of those numbers to another file, but without any duplicate numbers. You should assume that the input file is sorted from smallest to largest with one number on each line. After the program is run, the output file should contain all numbers that are in the original file, but no number should appear more than once. The numbers in the...
Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
Create a java program that has a code file with main() in it and another code...
Create a java program that has a code file with main() in it and another code file with a separate class. You will be creating objects of the class in the running program, just as the chapter example creates objects of the Account class. Your system handles employee records and processes payroll for them. Create a class called Employee that holds the following information: first name, last name, monthly salary, and sales bonus. The class should have all the gets...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT