Question

This assignment involves 2 Java programs 1) Write a Java program to read a CSV (Comma...

This assignment involves 2 Java programs 1) Write a Java program to read a CSV (Comma separated values) text file. The text file will contain comma separated values in each line. Each line contains data in this format: String(20), String(5),String(10), double. There will be multiple lines with each line containing the same number of values. Ask the user to enter the path for the CSV file for reading the file. After reading the data from the file output the data to the console (one line at a time) with the data in each line in properly aligned columns. Then write the data to a serialized file called "assignment2.ser" to the local project folder .

2) In the second program, read the serialized file and output the data in columns to the console (one line at a time) with the data in each line in properly aligned columns.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note: Create "input.csv" file in D drive with following demo data

String11,String12,String13,Double1
String21,String22,String23,Double2
String31,String32,String33,Double3
String41,String42,String43,Double4
String51,String52,String53,Double5

Code:

import java.util.Arrays;
import java.io.*;
public class SerializedFile implements Serializable
{
String line;
String data[][] = new String[100][4];
int count = 0;

void readFromFile()
    {
    try
      {
      // BufferedReader object to read data from file
      BufferedReader read = new BufferedReader(new FileReader("d:\\input.csv"));

      while ((line = read.readLine()) != null) //read data line by line
         {
         data[count] = line.split(","); //split into array of strings
         count++; //line counter
         }
      read.close(); //close input file
      }
    catch(FileNotFoundException e) //exception for file not found
      {
      System.out.println("File not found.");
      }
    catch(Exception ex) //other exceptions like permission denied
      {
      System.out.println(ex.toString());
      }
    }


void printData()   //to print data
    {
    for(int i=0; i<count; i++)
      {
      System.out.println(Arrays.toString(data[i])); //print data
      //you may also print one by one. eg data[i][0], data[i][1]....
      }
    }


public static void main(String arga[]) //main method to control the program
    {
    SerializedFile obj = new SerializedFile(); //crating object of class. it will call constructor
    obj.readFromFile();

    System.out.println("\nReading Data from File\n");
    obj.printData();

    String filename = "assignment2.ser";

    // Serialization is a process to convert objects into a writable byte stream.
    //Once converted into a byte-stream, these objects can be written to a file.
    try
           {
            //Saving of object in a file
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);

            // Method for serialization of object
            out.writeObject(obj);

            out.close();
            file.close();

            System.out.println("\nObject has been serialized\n");
            }
        catch(IOException ex)
            {
            System.out.println("IOException is caught");
            }

    SerializedFile newObj = null;

    System.out.println("\nReading Data from Deserialized object\n");
    obj.printData();
    // Deserialization is process of reading back
    try
            {
            // Reading the object from a file
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);

            // Method for deserialization of object
            newObj = (SerializedFile)in.readObject();

            in.close();
            file.close();
            }

        catch(IOException ex)
            {
            System.out.println("IOException is caught");
            }

        catch(ClassNotFoundException ex)
            {
            System.out.println("ClassNotFoundException is caught");
            }
    }
}

Output:

     

Code Screenshot:

Add a comment
Know the answer?
Add Answer to:
This assignment involves 2 Java programs 1) Write a Java program to read a CSV (Comma...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can you write with comments please. Thank you. Write a Java Program that asks the user...

    Can you write with comments please. Thank you. Write a Java Program that asks the user to enter the responses on the Console and write the responses to a text file called responses.txt (in the same directory as the program) Write another JAVA prorgram to read responses.txt file and calculate the frequency of each rating in the file and output the number and frequency in two columns (number, frequency) on the Console.

  • IN JAVA. Write a program that reads a file (provided as attachment to this assignment) and...

    IN JAVA. Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. For example if file input is: This is a test File output should be 1. This is a test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BELOW FROM NOTEPAD FILE. This file contains lines of text to determine if you can properly read and write from a file.

  • Write a C++ program that will input data from a Comma-separated values (.csv) file and output...

    Write a C++ program that will input data from a Comma-separated values (.csv) file and output some information about it. This program uses a csv file from Yahoo Finance (.csv) filename : SBUX.csv 1. Output the name of the ticker to the console screen (without the “.csv”) 2. Output the start date and end date that was found in the file 3. Output how many trading day(s) existed in the file 4. Prompt the use to input a number of...

  • Write a Java program to read customer details from an input text file corresponding to problem...

    Write a Java program to read customer details from an input text file corresponding to problem under PA07/Q1, Movie Ticketing System The input text file i.e. customers.txt has customer details in the following format: A sample data line is provided below. “John Doe”, 1234, “Movie 1”, 12.99, 1.99, 2.15, 13.99 Customer Name Member ID Movie Name Ticket Cost Total Discount Sales Tax Net Movie Ticket Cost Note: if a customer is non-member, then the corresponding memberID field is empty in...

  • Problem 1 (Reading Statistics) Write a function called read_stats(filename) that takes a csv (comma separated values)...

    Problem 1 (Reading Statistics) Write a function called read_stats(filename) that takes a csv (comma separated values) filename as an argument and returns a 2D list containing the statistics in that file. The returned list should contain lists of stats for each crime reported and should not include the header line from the file. The file crime_in_vancouver.csv (included in the folder) has the following structure: • The first row provides headers for each column • Each subsequent row represents the stats...

  • Java program Program: Grade Stats In this program you will create a utility to calculate and...

    Java program Program: Grade Stats In this program you will create a utility to calculate and display various statistics about the grades of a class. In particular, you will read a CSV file (comma separated value) that stores the grades for a class, and then print out various statistics, either for the whole class, individual assignments, or individual students Things you will learn Robustly parsing simple text files Defining your own objects and using them in a program Handling multiple...

  • Need help with java programming. Here is what I need to do: Write a Java program...

    Need help with java programming. Here is what I need to do: Write a Java program that could help test programs that use text files. Your program will copy an input file to standard output, but whenever it sees a “$integer”, will replace that variable by a corresponding value in a 2ndfile, which will be called the “variable value file”. The requirements for the assignment: 1.     The input and variable value file are both text files that will be specified in...

  • What to submit: your answers to exercises 2. Write a Java program to perform the following...

    What to submit: your answers to exercises 2. Write a Java program to perform the following tasks: The program should ask the user for the name of an input file and the name of an output file. It should then open the input file as a text file (if the input file does not exist it should throw an exception) and read the contents line by line. It should also open the output file as a text file and write...

  • According to Wikipedia , a comma-separated values (CSV) file is a delimited text file that uses...

    According to Wikipedia , a comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. A company has text data that is not...

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT