Serialized Object File Output is empty - java

I am trying to create a file that stores high scores for a game that I am making. I am using a serializer to write my arrays into a file. The file is created upon running my code but the file is empty (0 bytes). I'm not getting any errors. Can anyone tell me why the file does not contain my data?
public class BestTimes implements Serializable
{
BestTimes[] beginner = new BestTimes[2];
public static void main(String args[]) throws IOException {
BestTimes bestTimes = new BestTimes();
bestTimes.outputToFile();
}
public BestTimes() {
beginner[0] = new BestTimes(1, "John", 10.5);
beginner[1] = new BestTimes(2, "James", 20.3);
}
public int ranking;
public String playerName;
public double time;
public BestTimes(int r, String p, double t)
{
ranking = r;
playerName = p;
time = t;
}
public void outputToFile() throws IOException {
try(FileOutputStream f = new FileOutputStream("bestTimes.txt")) {
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(beginner);
s.flush();
s.close();
} finally {
FileOutputStream f = new FileOutputStream("bestTimes.txt");
f.close();
}
}
}

Of course it's empty. You created a new one in the finally block.
Just remove that code.

Related

Reading object from a file and saving it into ArrayList

I have a problem with reading specific object from a file and saving it into ArrayList.
First I write a single customer using writeCustomer(). Then I write all records from List customerList and save them to the file. This works great.
Then I want to read the saved file so I read one line using readCustomer(). This method returns one Customer and then I want to return a list with all Clients using readData() and read it, I have nullPointerException in line list.add(readCustomer(bufferedReader));
My Class Customer has one constructor and is has an override method toString().
public class SaveCustomers {
public static void main(String[] args) throws IOException {
List<Customers> customersList = new ArrayList<>();
customersList.add(new Customers("ABC", 10));
customersList.add(new Customers("SGS", 20));
customersList.add(new Customers("FSD", 30));
try (PrintWriter out = new PrintWriter("customer.txt", "UTF-8"))
{ writeData(customersList, out); }
BufferedReader bufferedReader = new BufferedReader(new FileReader("customer.txt"));
List<Customers> newList = readData(bufferedReader);
for(Customers c: newList){
System.out.println(c);
}
}
private static void writeCustomer(PrintWriter out, Customers customers){
out.println(customers.getName()+"|"+customers.getTarrif());
}
private static void writeData(List<Customers> customersList, PrintWriter out){
for(Customers c:customersList){
writeCustomer(out, c);
}
}
public static Customers readCustomer(BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine();
String [] tokens = line.split("\\|");
String name = tokens[0];
int time = Integer.valueOf(tokens[1]);
return new Customers(name, time);
}
public static List<Customers> readData(BufferedReader bufferedReader) throws IOException {
List<Customers> list = new ArrayList<>();
while (bufferedReader.readLine() != null) {
list.add(readCustomer(bufferedReader));
}
return list;
}}
You are close to the solution ;)
In method :
readData(BufferedReader bufferedReader)
Just change this line
for(Customers l : list) {
to this one :
while (bufferedReader.ready()) {

Error while file reading

I wanna make an ArrayList of objects of my own class named Room and store it to file. I have successfully wrote it but when I read it back to ArrayList it gives me the following error
error: incompatible types
temp_read=filereader.readObject();
^
required: Room
found: Object
My code:
public class Room implements Serializable
{
public String room_number="";
public String teacher_name="";
public String Day_of_class="";
public String class_name="";
public My_Time start_time;
public My_Time end_time;
public Room()
{
room_number="";
teacher_name="";
Day_of_class="";
class_name="";
start_time=new My_Time();
end_time=new My_Time();
}
public Room(String r_name ,String t_name ,String cl,String day,
int hr1,int min1,String am1,int hr2,int min2,String am2 )
{
room_number=r_name;
teacher_name=t_name;
Day_of_class=day;
class_name=cl;
start_time=new My_Time(hr1,min1,am1);
end_time=new My_Time(hr2,min2,am2);
}
public void file_room_writer(/* ArrayList<Room> temp_room ,*/String str )
{
/// file writing handling`enter code here`
//--------------------------------------------------
// Room a1 =temp_room;
try {
File file = new File(str+".txt");
FileOutputStream file_stream=new FileOutputStream(file);
ObjectOutputStream fileWriter = new ObjectOutputStream(file_stream);
fileWriter.writeObject(class_storing);
fileWriter.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null,"Exception at file writing ");
}
}
public void file_room_reader(String str )
{
/// file handlingg
//--------------------------------------------------
ArrayList<Room> contain_room ;
try {
File file = new File(str+".txt");
FileInputStream file_stream=new FileInputStream(file);
ObjectInputStream filereader = new ObjectInputStream(file_stream);
temp_read=filereader.readObject();
contain_room=(ArrayList<Room>)filereader.readObject();
filereader.close();
}
catch(Exception e1)
{
e1.getStackTrace();
JOptionPane.showMessageDialog(null,"Exception at file Reading ");
}
}
The readObject method returns an object - you have to try and cast it to a Room.
temp_read = (Room) filereader.readObject();
readObject() returns Object , you'll have to downcast it to the type of temp_read.
Assuming Room is the type of temp_read
temp_read = (Room) filereader.readObject();

Compile time error when retrieving objects from return values in a different class.

I am receiving a compile time error with the following code. The first code block scans in a text file and provides a get method for retrieving the largest value in the Array List. That block of code compiles fine. The second block of code is where I'm having difficulty. I'm fairly new to programming and am having difficulty understanding where I've made my error.
public class DataAnalyzer {
public DataAnalyzer(File data) throws FileNotFoundException
{
{
List<Integer> rawFileData = new ArrayList<>();
FileReader file = new FileReader("info.txt");
try (Scanner in = new Scanner(file)) {
while(in.hasNext())
{
rawFileData.add(in.nextInt());
}
}
}
}
public int getLargest(List<Integer> rawFileData){
return Collections.max(rawFileData);
}
}
This is the Tester Class I am attempting to implement. I am receiving a compile time error.
public class DataAnalyzerTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter your fileName: ");
}
public void printLargest(DataAnalyzer rawFileData)
{
rawFileData.getLargest();
System.out.println(rawFileData.getLargest());
}
}
I tryed to run your code, you have problem in the line 14 of the DataAnalyzerTester, you need to pass a parameter of List<Integer> to the method getLargest().
Try your Tester this way:
public class DataAnalyzerTester {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter your fileName: ");
}
public void printLargest(DataAnalyzer rawFileData) {
List<Integer> example = new ArrayList<Integer>();
example.add(0);
example.add(1);
example.add(2);
int result = rawFileData.getLargest(example);
System.out.println(result);
}
}
-------------- EDIT --------------------
Try something like this:
public class DataAnalyzer {
private List<Integer> rawFileData;
public DataAnalyzer(String fileName) throws FileNotFoundException {
rawFileData = new ArrayList<>();
FileReader file = new FileReader(fileName);
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
rawFileData.add(in.nextInt());
}
}
}
public int getLargest() {
return Collections.max(rawFileData);
}
}
public class DataAnalyzerTester {
public static void main(String[] args) throws FileNotFoundException {
DataAnalyzer analizer = new DataAnalyzer("info.txt");
System.out.println(analizer.getLargest());
}
}

How to use ArrayList while adding something to another Class's constructor ?

I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));

ArrayList saved to textfile

I want to save the contents of my arraylist to a textfile. What I have so far is shown below, however instead of adding x.format("%s%s", "100", "control1"); to the textfile, I want to add objects from an arraylist, how do I go about this?
import java.util.*;
public class createfile
{
ArrayList<String> control = new ArrayList<String>();
private Formatter x;
public void openFile()
{
try {
x = new Formatter("ControlLog.txt");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: Your file has not been created");
}
}
public void addRecords()
{
x.format("%s%s", "100", "control1");
}
public void closeFile()
{
x.close();
}
}
public class complete
{
public static void main(String[] args)
{
createfile g = new createfile();
g.openFile();
g.addRecords();
g.closeFile();
}
}
Both ArrayList and String implement Serializable. Since you have an ArrayList of string you can write it to the file like this:
FileOutputStream fos = new FileOutputStream("path/to/file");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(myArrayList); //Where my array list is the one you created
out.close();
Here is a really good tutorial that shows you how to write java objects to a file.
The written objects can be read back from the file in a similar way.
FileInputStream in = new FileInputStream("path/to/file");
ObjectInputStream is = new ObjectInputStream(in);
myArrayList = (ArrayList<String>) is.readObject(); //Note that you will get an unchecked warning here
is.close()
Here is a tutorial on how to read objects back from a file.

Categories

Resources