How can save and print Arraylist to a file? - java

import java.util.*;
import java.io.*;
class Book implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String author;
public String getAuthor() {
return author;
}
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public void disPlay() {
System.out.print("Book name : " + name);
System.out.println("\tAuthor name : " + author);
}
}
public class Print {
public static void main(String[] args) throws Exception {
writeList();
List<Book> list = readList();
for (Book obj : list)
System.out.println(obj);
}
public static List<Book> readList() throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.dat"));
#SuppressWarnings("unchecked")
List<Book> readObject = (List<Book>) in.readObject();
in.close();
return readList();
}
public static void writeList() throws Exception {
List<Book> list = new ArrayList<>();
ObjectOutputStream out = null;
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter the book, author name : ");
String name = scan.next();
String author = scan.next();
list.add(new Book(name, author));
System.out.print("If you want to save to the list -1, if you don't want, enter 1 : ");
int choice = scan.nextInt();
out = new ObjectOutputStream(new FileOutputStream("object.dat"));
out.flush();
out.close();
System.out.print("Save the list to a file");
}
}
}
I try to get the ArrayList object stored in the file (object.dat), save the Book object in the ArrayList, and then save the ArrayList where the Book object is stored in the file before the end of the program.
The result I want is,
[Results When Program First Runs]
There are no saved values
Enter the book, author name : Harrypotter jkrowling
If you want to save to the list -1, if you don't want, enter 1 : -1
Save the list to a file
and,
[Results on Second and Later]
---Outputs the value stored in the file name---
Book name : Harrypotter
Author name : jkrowling
Enter the book, author name : Twilight StephenieMeyer
If you want to save to the list -1, if you don't want, enter 1 : 1
Save the list to a file
I'd like to print it out like this, but what should I do?

Here is the general way of writing to file in java.
import java.io.FileWriter; // Import the FileWriter class
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Write into file here! ");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}

To simplify your code and avoid boilerplates I’d recommend you to look towards specific tools and libs working with files.
There is a good article about loading and reading files using Spring:
Spring Resource
For writing content to a file look towards eg “Apache Commons IO” library provides useful helper methods like:
FileUtils.write(new File(“File.txt"), "Content Text", "UTF-8");
In any case investigate these tools and then think about adopting your requirements in them.

try {
FileWriter writer = new FileWriter("Book.txt");
for(int i = 0 ; i < arraylist.size(); i++){
writer.write(arraylist.get(i).getName();
writer.write(arraylist.get(i).getAuthor();
}
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

Related

For loop to write data to file Java

I need to implement a method called saveWorksToFile according to the Javadoc in the code. The format of the output written to the file should be the following this pattern:
where ARTIST_NAME is the name of the artist, NUM_WORKS is the number of works
of that artist, and WORK_1, WORK_2, etc. are the toString representations of
each of that artist's works.
The last work should not have a line separator after it.
If an artist has no works, then the first three lines of the above format should
be written, where the “-----” line has a line separator after it.
And this is the code I have:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class Artist {
static class Work {
String name; // e.g. "Mona Lisa"
int yearCreated; // e.g. 1506
String medium; // e.g. "Oil on poplar panel"
public Work(String name, int yearCreated, String medium) {
this.name = name;
this.yearCreated = yearCreated;
this.medium = medium;
}
public String getName() { return name; }
public int getYearCreated() { return yearCreated; }
public String getMedium() { return medium; }
#Override
public String toString() {
return name + "|" + yearCreated + "|" + medium;
}
}
private String name; // e.g. "Henri Matisse"
private List<Work> works = new ArrayList<>();
public Artist(String name) {
this.name = name;
}
public void addWork(Work work) {
this.works.add(work);
}
/**
* Writes the toString representation of each of this artist's works to the
* given writer. Also writes header lines containing the artist's name and
* number of works.
*
* If an IOException occurs, the message "IOException occurred" should be
* printed to System.out.
*
* #param writer writer to write this artist's works to
*/
public void saveWorksToFile(Writer writer) {
// write your code here
try {
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write(this.name);
buffer.newLine();
buffer.write("works: " + this.works.size());
buffer.close();
}
catch (IOException e) {
System.out.println("IOException occurred");
}
}
}
I got these errors:
=> org.junit.ComparisonFailure: The expected value is: Vincent van Gogh[newline]works: 0[newline]-----[newline] expected:<...nt van Gogh
=> org.junit.ComparisonFailure: The expected value is: Vincent van Gogh[newline]works: 0[newline]-----[newline] expected:<...nt van Gogh
=> org.junit.ComparisonFailure: The expected value is: Vincent van Gogh[newline]works: 0[newline]-----[newline] expected:<...nt van Gogh
=> org.junit.ComparisonFailure: The expected value is: Claude Monet[newline]works: 2[newline]-----[newline]Bridge over a Pond of Water Lilies|1899|Oil on canvas[newline]Impression, Sunrise|1872|Oil on canvas expected:<...laude Monet
=> org.junit.ComparisonFailure: The expected value is: Claude Monet[newline]works: 2[newline]-----[newline]Bridge over a Pond of Water Lilies|1899|Oil on canvas[newline]Impression, Sunrise|1872|Oil on canvas expected:<...laude Monet
=> org.junit.ComparisonFailure: The expected value is: Henry Matisse[newline]works: 1[newline]-----[newline]Woman with a Hat|1905|Oil on canvas expected:<...nry Matisse
=> org.junit.ComparisonFailure: The expected value is: Henry Matisse[newline]works: 1[newline]-----[newline]Woman with a Hat|1905|Oil on canvas expected:<...nry Matisse
=> org.junit.ComparisonFailure: The expected value is: Henry Matisse[newline]works: 1[newline]-----[newline]Woman with a Hat|1905|Oil on canvas expected:<...nry Matisse
=> org.junit.ComparisonFailure: The expected value is: Claude Monet[newline]works: 2[newline]-----[newline]Bridge over a Pond of Water Lilies|1899|Oil on canvas[newline]Impression, Sunrise|1872|Oil on canvas expected:<...laude Monet
I have difficulties on making a new line, I tried both \n and newLine() method but it doesn't work. And also showing the number of works on the list should be correct. And for the loop, I think I should use for loop in this case to loop over the art works.
Any hints/ help would be great, thank you!
Below is my code for method saveWorksToFile. It is the only part of the code in your question that I changed. (Notes after the code.)
public void saveWorksToFile(Writer writer) {
try {
writer.write(this.name);
writer.write(System.lineSeparator());
writer.write("works: " + this.works.size());
writer.write(System.lineSeparator());
writer.write("---");
writer.write(System.lineSeparator());
boolean first = true;
for (Work work : works) {
if (first) {
first = false;
}
else {
writer.write(System.lineSeparator());
}
writer.write(work.toString());
}
}
catch (IOException e) {
System.out.println("IOException occurred");
}
}
You are not meant to wrap the Writer parameter in a BufferedWriter. In general, for any method, you usually should not need to cast the parameter. Hence, in the above code, I use only the methods of class Writer. Also note that I do not close Writer since that should be left to the code that invoked method saveWorksToFile.
In order to write a line separator, I call method lineSeparator of class java.lang.System.
In order to print all the artist's works one per line, I use a loop.
In order to ensure that the last entry in the artist's list of works is written without a line separator, the first work is written without a line separator and every subsequent work is written with a preceding line separator.
Here is a method I wrote to test the above code. It uses class java.io.StringWriter which is a subclass of Writer since class Writer is abstract and has no public constructor. In general, you cannot instantiate an abstract class. You need to use a concrete subclass. I use StringWriter so as to be able to print its contents easily to the screen. You can use class java.io.FileWriter if you want to write to an actual file.
/**
* import java.io.StringWriter
*/
public static void main(String[] args) {
Artist artist = new Artist("Vincent van Gogh");
StringWriter sw = new StringWriter();
artist.saveWorksToFile(sw);
System.out.print(sw);
System.out.println();
artist = new Artist("Claude Monet");
Work work = new Work("Bridge over a Pond of Water Lilies", 1899, "Oil on canvas");
artist.addWork(work);
work = new Work("Impression, Sunrise", 1872, "Oil on canvas");
artist.addWork(work);
sw = new StringWriter();
artist.saveWorksToFile(sw);
System.out.print(sw);
System.out.println();
artist = new Artist("Henri Matisse");
work = new Work("Woman with a Hat", 1905, "Oil on canvas");
artist.addWork(work);
sw = new StringWriter();
artist.saveWorksToFile(sw);
System.out.print(sw);
}
This is the output I got when I ran the above main method.
Vincent van Gogh
works: 0
---
Claude Monet
works: 2
---
Bridge over a Pond of Water Lilies|1899|Oil on canvas
Impression, Sunrise|1872|Oil on canvas
Henry Matisse
works: 1
---
Woman with a Hat|1905|Oil on canvas
you can use json format to save your data easily and orginized like this
public void saveWorksToFile(OutputStreamWriter writer) {
// write your code here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("ARTIST_NAME",this.name);
jsonObject.put("NUM_WORKS",this.works.size());
for (int i=0;i<works.size();i++) {
jsonObject.put("work_" + i, works.get(i).toString());
// you can save work as a byte array or json string so you could easily import the data back
}
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write(jsonObject.toString()+"\n");
buffer.close();
}
catch (IOException | JSONException e) {
System.out.println("IOException occurred");
}
}
public Artist readFromFile(File file){
Artist artist = null;
FileReader fileReader = null;
String line= null;
BufferedReader bufferedReader;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
while (line != null){
line += "\n";
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(line);
String name = jsonObject.get("ARTIST_NAME").toString();
int works_num = Integer.parseInt(jsonObject.get("NUM_WORKS").toString());
// here you can import the works as a string.
artist = new Artist(name);
} catch (JSONException e) {
e.printStackTrace();
}
line = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return artist;
}
My advice is that you separate classes, sometimes it is difficult to figure out problems. I separated them like this.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Artist {
private String name; // e.g. "Henri Matisse"
private List<Work> works = new ArrayList<>();
public Artist(String name) {
this.name = name;
}
public void addWork(Work work) {
this.works.add(work);
}
public void saveWork(){
try{
BufferedWriter writer = new BufferedWriter(
new FileWriter("path where want to save"));
writer.write(this.name);
writer.newLine();
writer.write("works: " + this.works.size());
writer.newLine();
this.works.forEach(work -> {
try {
writer.write(work.name);
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
});
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Work {
String name; // e.g. "Mona Lisa"
int yearCreated; // e.g. 1506
String medium; // e.g. "Oil on poplar panel"
public Work(String name, int yearCreated, String medium) {
this.name = name;
this.yearCreated = yearCreated;
this.medium = medium;
}
public String getName() { return name; }
public int getYearCreated() { return yearCreated; }
public String getMedium() { return medium; }
#Override
public String toString() {
return name + "|" + yearCreated + "|" + medium;
}
}
public class Main {
public static void main(String[] args) {
Work work1 = new Work("Fast1",2019,"ss");
Work work2 = new Work("Fast2",2019,"ss");
Artist artist = new Artist("Artist_Tom_Cruise");
artist.addWork(work1);
artist.addWork(work2);
artist.saveWork();
}
}

EOFException when I extract the Object Input/Out put Stream

I use ObjectInput/Output to initialize the hashmap named temp and it put all entry of the hashmap called map that is initialized to new and then use OutputStream to save it in file formatting is .ser
this work perfectly...
import java.io.*;
import java.util.HashMap;
public class PlayerInfo implements Serializable {
ObjectOutputStream out;
ObjectInputStream in;
File userData =new File("path.ser");
HashMap map ;
HashMap temp;
private Integer ID;
String name ;
boolean isItNull =false;
public static void main(String[] args) {
new PlayerInfo();
}
PlayerInfo(){
try {
initializeHashMap();
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void initializeHashMap(){
try {
//initialize ObjectInputStream in same method when I use it and close it then
in =new ObjectInputStream(new FileInputStream(userData));
if (isItNull){
temp =new HashMap<Integer,PlayerInfo>();
}else {
map =new HashMap<Integer,PlayerInfo>();
temp = (HashMap<Integer, PlayerInfo>) in.readObject();
in.close();
}
}catch (Exception e){
isItNull =true;
initializeHashMap();
}
}
private void getInfo(){
System.out.println("Ok we are in get info so write your ID:-");
int id = 10;
}
#SuppressWarnings("unchecked")
private void createInfo()throws IOException{
//same here initialize ObjectOutputStreamin same method when I use it and close it then
out =new ObjectOutputStream(new FileOutputStream(userData));
System.out.println("Ok we are in create info so write your ID:-");
ID =10;
String scnS ="Mohammed";
System.out.println("Write your name");
map.put(ID,new PlayerInfo(scnS));
temp.putAll(map);
System.out.println("Saving....");
out.writeObject(temp);
out.close();
}
public PlayerInfo(String name){
this.name =name;
}
}
but this throw EFOException
import java.io.*;
import java.util.HashMap;
public class PlayerInfo implements Serializable {
ObjectOutputStream out;
ObjectInputStream in;
File userData =new File("path.ser");
HashMap map ;
HashMap temp;
private Integer ID;
String name ;
boolean isItNull =false;
public static void main(String[] args) {
new PlayerInfo();
}
PlayerInfo(){
try {
openTheOutPutObjectStreamer();
openTheInPutObjectStreamer();
initializeHashMap();
}catch (Exception e){
e.printStackTrace();
}
}
//here I initialize it in separated method
private void openTheOutPutObjectStreamer()throws IOException{
out =new ObjectOutputStream(new FileOutputStream(userData));
}
//same here I initialize it in separated method
private void openTheInPutObjectStreamer()throws IOException{
in =new ObjectInputStream(new FileInputStream(userData));
}
#SuppressWarnings("unchecked")
private void initializeHashMap(){
try {
if (isItNull){
temp =new HashMap<Integer,PlayerInfo>();
}else {
map =new HashMap<Integer,PlayerInfo>();
temp = (HashMap<Integer, PlayerInfo>) in.readObject();
in.close();
}
}catch (Exception e){
isItNull =true;
initializeHashMap();
}
}
#SuppressWarnings("unchecked")
private void createInfo()throws IOException{
System.out.println("Ok we are in create info so write your ID:-");
ID =10;
String scnS ="Mohammed";
System.out.println("Write your name");
map.put(ID,new PlayerInfo(scnS));
temp.putAll(map);
System.out.println("Saving....");
out.writeObject(temp);
out.close();
}
public PlayerInfo(String name){
this.name =name;
}
}
if you see it the difference is only separate the Object Input/Output to a method and call them
and I am sorry I am a newbie in this website
I don't know a lot about IO but it seems like I cant separate it to methods and call it?
The problem is that in your first code you (correctly) open an input stream uses it and then closes it before doing anything else to the same file but in your second code version you also open the output stream on the same file before having read it and that output stream puts the marker (where to read or write) at the end of the file so when you use your input stream you get an End of file error.
Changing you code to this should work
openTheInPutObjectStreamer();
initializeHashMap();
openTheOutPutObjectStreamer();

Storing Objects of an array into CSV file and reading them with specific arguments for GUI

As a part of my assignment I had to store objects of an array in a flat-file and retrieve them when certain criteria was met. I can save the objects fine but when retrieving them I have an issue with getting more than one value, I understand what is going wrong but I am struggling to find a solution. Here is the concept of whats happening.
Button no 10,A (R1S10 in the code)is my testing button, When I click it it creates an event that I will show below.
Click event for button 10A -
private void R1S10ActionPerformed(java.awt.event.ActionEvent evt) {
seats.add(seat1);
if (R1S10.getBackground().equals(Color.red) &&(IsSeatBooked().equals("true"))){
Component frame = null;
JOptionPane.showMessageDialog(frame, "Seat UnBooked");
seat1.setBooked("false");
seat1.setName("");
R1S10.setBackground(Color.yellow);
try {
reader();
writer();
//String booked = "true";
//Pass String booked into csv file
} catch (IOException ex) {
Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
Component frame = null;
String name = JOptionPane.showInputDialog(frame, "Please enter name of Customer booking");
if (name.isEmpty()) {
JOptionPane.showMessageDialog(frame, "No value entered");
} else if (name != null) {
seat1.setName(name);
seat1.setBooked("true");
R1S10.setBackground(Color.red);
JOptionPane.showMessageDialog(frame, "Your Booking has been placed");
try {
writer();
reader();
//String booked = "true";
//Pass String booked into csv file
} catch (IOException ex) {
Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Followed by the screen below -
Outcome -
And when the button is pressed again -
I am using three methods in this SeatingPlan.java - writer(),reader() and IsSeatBooked().
SeatingPlan -
public class SeatingPlan extends javax.swing.JFrame {
/**
* Creates new form SeatingPlan
*/
String seatNo, name, bookedSeat;
FileWriter fileWriter = null;
List<Seat> seats = new ArrayList<Seat>();
//Seat Object Declaration
Seat seat1 = new Seat("R1S10","","false");
Seat seat2 = new Seat("R1S9", "", "false");
String fileName = "seat.csv";
writer -
public void writer() throws IOException {
//Delimiter used in CSV file
final String NEW_LINE_SEPARATOR = "\n", COMMA_DELIMITER = ",";
//CSV file header
final String FILE_HEADER = "seatID,name,booked";
//fileName = System.getProperty("user.home") + "/seat.csv";
try {
fileWriter = new FileWriter(fileName);
//Write the CSV file header
fileWriter.append(FILE_HEADER.toString());
//Add a new line separator after the header
fileWriter.append(NEW_LINE_SEPARATOR);
//Write a new student object list to the CSV file
for (Seat seat : seats) {
fileWriter.append(String.valueOf(seat.getSeatID()));
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(seat.getName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(seat.isBooked());
fileWriter.append(NEW_LINE_SEPARATOR);
}
System.out.println("CSV file was created successfully !!!");
} catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
} finally {
fileWriter.flush();
fileWriter.close();
}
}
reader -
public void reader() {
//Delimiter used in CSV file
final String COMMA_DELIMITER = ",";
//Student attributes index
final int SEAT_ID_IDX = 0;
final int SEAT_NAME_IDX = 1;
final int SEAT_BOOKED = 2;
//private static final int STUDENT_LNAME_IDX = 2;
BufferedReader fileReader = null;
try {
//Create a new list of student to be filled by CSV file data
List<Seat> seats = new ArrayList<>();
String line = "";
//Create the file reader
fileReader = new BufferedReader(new FileReader(fileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
//Create a new seat object and fill his data
Seat seat = new Seat(tokens[SEAT_ID_IDX],
tokens[SEAT_NAME_IDX], tokens[SEAT_BOOKED]);
seats.add(seat);
seatNo = tokens[SEAT_ID_IDX];
//System.out.println("Seat Number: " + seatNo);
bookedSeat = tokens[SEAT_BOOKED];
}
}
//Print the new student list
for (Seat seat : seats) {
System.out.println(seat.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}//end reader
SeatingPlan - This if where I have tried to have the arguments controlling the outcome but IsBooked is colliding when multiple seats are selected.
public SeatingPlan() throws IOException {
setVisible(true);
initComponents();
//reader();
ColourSectionGold();
ColourSectionBronze();
reader();
if(R1S10.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true"))){ R1S10.setBackground(Color.red);}
//if(R1S9.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true2"))){ R1S9.setBackground(Color.red);}
}
IsSeatBooked -
public String IsSeatBooked(){
return bookedSeat;
}//end IsSeatBooked
Im using the method above as my argument to see whether a seat is booked or not, but when a new seat is click it sets the whole value of 'bookedSeat' - which leaves the system not working correctly. I understand the code is not very efficient but is there any temporary fix for this problem, if I have explained it correctly.
Also I will include my class for Seat -
public class Seat {
private String seatID;
private String booked;
private String name;
private int price;
public Seat(String seatID,String name,String booked){
this.seatID = seatID;
this.booked = "";
this.name = name;
this.price = price;
}
public String getSeatID() {
return seatID;
}
public void setSeatID(String seatID) {
this.seatID = seatID;
}
public String isBooked() {
return booked;
}
public void setBooked(String booked) {
this.booked = booked;
}
public String getStatus(){
return booked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPrice() {
this.price = price;
}}//end class Seat
And a look at the CSV file that is created -
I wish to be able to click more than one button and save its state, Button 10 works fine at the moment, but as IsBooked only has one value at a time it clashes.
If you took the time to check this out, I appreciate it. Any constructive criticism is helpful and any ideas would be great!
Thanks,
Paddy.
Too much code to look at to see exactly what you are doing.
Instead of using your csv file, you could create a Properties file. The Propertiesfile will store the data in the form of:
key:data
So in your case the key would be the id: A1, A2... and the data would be the name of the person who booked the seat.
So the file would start out as empty. When you create the GUI you would create a loop that checks each id to see if an entry is found in the Properties field. If it is found then you display the seat as taken, otherwise it is empty.
Then whenever you want to book a seat you just use the setProperty(...) method.
The Properties class has load(...) and store(...) methods.
So the Properties class allows you to easily manage a flat file database with minimal effort.
Note, you would never have variable names like R1S10. That would requirement 100 different variables with if/else statements. Instead you would extend JButton and pass in the row and seat as parameters the button. Then in the ActionListener for the button you can access the row/seat information to built the ID used as the key for the properties file.
Edit:
Couldn't quite make the loop that checks if the ID is in the properties file.
If the property is null, the seath is empty.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Properties properties = new Properties();
properties.setProperty("A2", "Smith");
properties.setProperty("C3", "Jones");
String[] rows = { "A", "B", "C", "D" };
int seats = 4;
for (int row = 0; row < rows.length; row++)
{
for (int seat = 1; seat <= seats; seat++)
{
String key = rows[row] + seat;
String property = properties.getProperty( key );
System.out.println(key + " : " + property);
}
}
}
}

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();

Java save function won't overwrite

I have created an object that i then added into an ArrayList. I then saved this arraylist into a .dat file using ObjectOutputStream. I know that the object has been created correctly because the next screen in the program loads directly from the object and the object can be read correctly from the file afterwards. The issue I am running into is that it appears that the object is saving, but it is not willing to be edited. Instead of editing the object in the arraylist, it is creating a new object and saving it again each time.
The code below shows the save function that is performed every time someone finishes the last screen. I am trying to make it so it will check to see if the student exists already in the array, and if so just edit the object. If the student doesn't exist, I want it to take selectedStudent (the object used for all GUI functions) and add it to the array "students" and write the array to the file, overwriting all previous data.
#SuppressWarnings("unchecked")
public static void saveNew() throws ClassNotFoundException, IOException{
int exists = -1;
try{
FileInputStream fis = new FileInputStream("records.dat");
ObjectInputStream in = new ObjectInputStream(fis);
students = (ArrayList<Student>) in.readObject();
in.close();
fis.close();
}
catch(IOException e){
e.printStackTrace();
}
try{
FileOutputStream fos = new FileOutputStream("records.dat", false);
ObjectOutputStream out = new ObjectOutputStream(fos);
for(int i = 0; i<students.size(); i++){
if(students.get(i).getID().equals(selectedStudent.getID())){
exists = i;
}
}
if(exists<0){
students.add(selectedStudent);
}
else{
students.set(i, selectedStudent);
}
out.writeObject(students);
out.close();
}
catch(IOException e){
e.printStackTrace();
}
}
Edit: I noticed that the variable exists was not being used to search for the object which was mistake number one, but I still have the issue where the saved object will not be changed until the method is called a second time. It seems to find it when it is run again, but when it is run the first time it will just create a new student with the edited name.
For example, the first student is created and saved. A second student is the created and saved. When the second student is being edited (without closing the program and restarting) it will, instead of editing the object in the file, create a new student object with the same information directly below the first. If the edit function is run a second time, the second student file is edited correctly but leaves the first as it was.
For a start I would edit these lines
if(students.get(i).getID().equals(selectedStudent.getID())){
exists = i;
}
to
if(students.get(i).getID().equals(selectedStudent.getID())){
System.out.println ("Got it");
exists = i;
break;
}
just to make sure it is working.
Also, you want to change the use of i to exists
else{
students.set(i, selectedStudent); // change to exists
}
I think you must check your variables (if you're reusing any) and initialization code.
The snippet you've posted seems to be fine, so I can't find the error on it.
Here goes a quite similar code that works. I hope it helps.
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Persistence {
public static void main(String[] args) throws Exception {
File f = new File("records.dat");
// f.delete();
if (!f.exists()){
f.createNewFile();
}
Persistence p = new Persistence();
if (p.peek() == null){
p.init(); //persist an empty list
}
p.saveNew(new Student("ID1","Some Value")); //must insert
p.saveNew(new Student("ID1","Some Other Value")); //must edit
p.saveNew(new Student("ID2","Some Value")); //must insert
ArrayList<Student> list = p.peek();
System.out.println(list);
}
private void save(ArrayList<Student> list) throws Exception{
FileOutputStream fos = new FileOutputStream("records.dat",false);//don't append
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.flush();
out.close();
fos.close();
}
private void init() throws Exception{
save(new ArrayList<Student>());
}
private ArrayList<Student> peek() throws Exception{
FileInputStream fis = new FileInputStream("records.dat");
try{
ObjectInputStream in = new ObjectInputStream(fis);
ArrayList<Student> students = (ArrayList<Student>) in.readObject();
return students;
}catch(EOFException eof){
return null;
}finally{
fis.close();
}
}
public void saveNew(Student s) throws Exception {
ArrayList<Student> students = peek();
int editIndex = -1;
for(int i=0;i<students.size();i++){
if (students.get(i).getID().equals(s.getID())){
editIndex = i;
break;
}
}
if (editIndex != -1){
students.set(editIndex, s); //replace
}else{
students.add(s); //add
}
save(students);
}
}
where
import java.io.Serializable;
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private String ID;
private String s;
public Student(String ID, String s) {
this.ID = ID;
this.s = s;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
#Override
public String toString() {
return "Student [ID=" + ID + ", s=" + s + "]";
}
}

Categories

Resources