Question

JAVA City Files Program: Deserialize objects from a file. Print the data contained in the fields...

JAVA City Files Program:

Deserialize objects from a file. Print the data contained in the fields of the objects to a plaintext file.

The Cities.dat binary file contains TEN serialized City objects. Each City object has name, population, latitude, and longitude fields. Prior to being serialized into the file, all ten objects had their fields set.

City Java:

public class City implements Serializable {

    private String name;
    private int population;
    private double latitude;
    private double longitude;

    public City(String n, int p, double lat, double lon) {
        name = n;
        population = p;
        latitude = lat;
        longitude = lon;
    }

    public String getName() {
        return name;
    }

    public double getLatitude() {
        return latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public int getPopulation() {
        return population;
    }

}

Program will need to first deserialize all ten City objects. You can use ten separate variables or put them in an array.

Program will need to produce a plaintext file where each line of the text file contains the city’s name, population, latitude, and longitude. Your program will need to use the “getter” methods of the deserialized City objects to retrieve the values of the four fields. The text file your program produces should have 10 lines; Each field should be separated by one space.

For example, if the first City object had its fields set to:

• (name) Newark

• (population) 277140

• (latitude) 40.735657

• (longitude) -74.172363

then the first line in the output text file should read:

Newark 277140 40.735657 -74.172363

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

Output.txt
Seattle 608660 47.606209 -122.332069
Las Vegas 583756 36.169941 -115.139832
Philadelphia 1580863 39.952583 -75.165222
New York 8175133 40.712776 -74.005974
Tampa 335709 27.950575 -82.457176
Austin 790390 30.267153 -97.743057
Denver 600158 39.739235 -104.99025
Minneapolis 382578 44.977753 -93.265015
Los Angeles 3792621 34.052235 -118.243683
Cleveland 396698 41.499321 -81.694359


output.txt screenshot


Code:

import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import Assignment.City;

public class CitySerializerDeserializer {

   //File to be created and read from
   private static final File file = new File("Cities.dat");

   public static void main(String[] args) {

       try {

           //de-serialize call
           List<City> deserializedCities = fetchCities();

           if(writeCitiesIntoFileAsPlainText(new File("output.txt"), deserializedCities)) {
              
               System.out.println("Cities written in plain text to output file");
           }

       } catch (Exception e) {
           e.printStackTrace();
       }

   } //end of main
  
   /*
   * De-serializes objects from file
   */
   public static List<City> fetchCities() throws ClassNotFoundException, IOException {

       List<City> cities = new ArrayList<>();
      
       City city = null;

       //try with resources which will automatically close the connections
       try (
               FileInputStream fis = new FileInputStream(file); //file reader
               ObjectInputStream oos = new ObjectInputStream(fis); // this reads objects from file
           ) {
          
           try {
           //reads the objects from file
               while ((city = (City) oos.readObject()) != null) {
                   cities.add(city);
               }
           } catch (EOFException e) {
               //end of file reached don't do anything
           }
       }

       //return the result read from file
       return cities;

   }
  
   /*
   * Writes the cities into file in below format
   * cityName population latitude longitude
   */
   public static boolean writeCitiesIntoFileAsPlainText(File file, List<City> cities) throws FileNotFoundException, IOException {
      
       //try with resources which will automatically close the connections
       try (
               FileWriter fos = new FileWriter(file);
               BufferedWriter bw = new BufferedWriter(fos) //writes in file
           ) {
          
           //take each city and write in file
           for(City city : cities) {
              
               //city written
               bw.write(
                           city.getName() +
                           " " +
                           city.getPopulation()
                           + " " + city.getLatitude()
                           + " " + city.getLongitude()
                           +"\n"
                       );
           }
       }
      
       //All went well then return true
       return true;
   }
}

Add a comment
Know the answer?
Add Answer to:
JAVA City Files Program: Deserialize objects from a file. Print the data contained in the fields...
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
  • Language: Java For this file, it should be concrete. I don't know how to write a...

    Language: Java For this file, it should be concrete. I don't know how to write a code with the following private field & associated getter methods: final String NAME - a constant that represents the name of a location final double LATITUDE - a constant that represents the latitude (x) of that location final double LONGITUDE - a constant double represents the longitude (y) of that location Then, create a following constructor to initialize Location(String name, double lat, double long)...

  • Question: Why doesn't my program turn CSV file into KML? Attached below is my java program...

    Question: Why doesn't my program turn CSV file into KML? Attached below is my java program along with my CSV file JAVA PROGRAM: import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; public class Library { private static Scanner s; private static PrintWriter outFile; public static void printHeader() { outFile.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); outFile.println("<kml xmlns=\"http://www.opengis.net/kml/2.2\">"); outFile.println("<Document>"); } // endmethod printHeader... public static void printData(String secterType,String name, String lat,String lon) { outFile.println("<Placemark>"); outFile.println(" <Style>"); outFile.println(" <LabelStyle>"); outFile.println(" <scale>0</scale>"); outFile.println(" </LabelStyle>"); outFile.println(" <IconStyle>"); outFile.println("...

  • (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text...

    (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text file named pets10.txt with 10 pets (or use the one below). Store this file in the same folder as your “class” file(s). The format is the same format used in the original homework problem. Each line in the file should contain a pet name (String), a comma, a pet’s age (int) in years, another comma, and a pet’s weight (double) in pounds. Perform the...

  • Write a program in Java that prompts a user for Name and id number. and then...

    Write a program in Java that prompts a user for Name and id number. and then the program outputs students GPA MAIN import java.util.StringTokenizer; import javax.swing.JOptionPane; public class Main {    public static void main(String[] args) {                       String thedata = JOptionPane.showInputDialog(null, "Please type in Student Name. ", "Student OOP Program", JOptionPane.INFORMATION_MESSAGE);        String name = thedata;        Student pupil = new Student(name);                   //add code here       ...

  • C++ Programming Hi! Sorry for all the material attached. I simply need help in writing the...

    C++ Programming Hi! Sorry for all the material attached. I simply need help in writing the Facility.cpp file and the other files are included in case they're needed for understanding. I was able to complete the mayday.cpp file but am stuck on Facility. The following link contains a tar file with the files provided by the professor. Thank you so much in advanced! http://web.cs.ucdavis.edu/~fgygi/ecs40/homework/hw4/ Closer.h: #ifndef CLOSER_H #define CLOSER_H #include <string> #include "gcdistance.h" struct Closer { const double latitude, longitude;...

  • I have a program that reads a file and then creates objects from the contents of...

    I have a program that reads a file and then creates objects from the contents of the file. How can I create a linked list of objects and use it with the package class instead of creating and using an array of objects? I am not allowed to use any arrays of objects or any java.util. lists in this program. Runner class: import java.util.Scanner; import java.io.*; class Runner { public static Package[] readFile() { try { File f = new...

  • Create a Java program that will store 10 student objects in an ArrayList, ArrayList<Student>. A student object con...

    Create a Java program that will store 10 student objects in an ArrayList, ArrayList<Student>. A student object consists of the following fields: int rollno String name String address Implement two comparator classes to sort student objects by name and by rollno (roll number). Implement your own selection sort method and place your code in a separate Java source file. Do not use a sort method from the Java collections library.

  • IN JAVA Ask the user for three employees. Store the data into three employee objects (use...

    IN JAVA Ask the user for three employees. Store the data into three employee objects (use the Employee class from the previous question). Display those employees in a table. On this question, you'll submit two files: Employee.java and some other file that has a main. Standard Input                 Bill Gates 1234 Engineering Engineer Elon Musk 4443 Business CEO Steve Jobs 9999 Creative Designer Required Output -- Employee Entry Form --\n Enter name\n Enter ID\n Enter department\n Enter position\n -- Employee...

  • Modify the program that you wrote for the last exercise in a file named Baseball9.java that...

    Modify the program that you wrote for the last exercise in a file named Baseball9.java that uses the Player class stored within an array. The program should read data from the file baseball.txt for input. The Player class should once again be stored in a file named Player.java, however Baseball9.java is the only file that you need to modify for this assignment. Once all of the input data from the file is stored in the array, code and invoke a...

  • 1. Employees and overriding a class method The Java program (check below) utilizes a superclass named...

    1. Employees and overriding a class method The Java program (check below) utilizes a superclass named EmployeePerson (check below) and two derived classes, EmployeeManager (check below) and EmployeeStaff (check below), each of which extends the EmployeePerson class. The main program creates objects of type EmployeeManager and EmployeeStaff and prints those objects. Run the program, which prints manager data only using the EmployeePerson class' printInfo method. Modify the EmployeeStaff class to override the EmployeePerson class' printInfo method and print all the...

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