Java FileReader cant find file - java

I seem to be having a problem reading the file and it is in the same directory as the source. I am using eclipse. I was wondering why it can't find the file.
Could not read the file
java.io.FileNotFoundException: Simulation.Configuration (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at hw1.Simulator.main(Simulator.java:24)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Simulates the interaction between objects
*/
public class Simulator {
public static void main(String[] args) {
ArrayList<Geotask> geotasks = new ArrayList<Geotask>();
int dimensionX = 0;
int dimensionY = 0;
int numberOfMobileObjects = 0;
MobileObject[] MoblieObjects = new MobileObject[numberOfMobileObjects];
int durationOfSimulation = 0;
try {
Scanner in = new Scanner( new FileReader("Simulation.Configuration"));
while (in.hasNext()) {
String simulation = in.next();
switch (simulation) {
case ("dimensionX:"):
dimensionX = in.nextInt();
break;
case ("dimensionY:"):
dimensionY = in.nextInt();
break;
case ("numberOfMoileObjects:"):
numberOfMobileObjects = in.nextInt();
break;
case ("WarningGeotask:"):
Geotask wTask = new WarningGeotask(in.nextInt(),
in.nextInt());
geotasks.add(wTask);
break;
case ("CounterGeotask:"):
Geotask cTask = new CounterGeotask(in.nextInt(),
in.nextInt());
geotasks.add(cTask);
break;
case ("PopulationMonitoringGeotask:"):
Geotask pTask = new PopulationMonitoringGeotask(
in.nextInt(), in.nextInt(), in.nextInt());
geotasks.add(pTask);
break;
case ("durationOfsimulation:"):
durationOfSimulation = in.nextInt();
break;
}
}
in.close();
System.out.println("unable to close configuration file!!!");
Ground ground = new Ground(dimensionX, dimensionY);
MobileObject mobile = null;
for (Geotask tsk : geotasks) {
ground.addGeotask(tsk);
}
for (int i = 0; i < numberOfMobileObjects; i++) {
mobile = new MobileObject(i, i % dimensionX, i % dimensionY, 1,
i % 8, ground);
MoblieObjects[i] = mobile;
for (Geotask tsk : geotasks) {
if (mobile.getCurrentX() == tsk.getX()
&& mobile.getCurrentY() == tsk.getY()) {
tsk.moveIn(mobile);
}
}
}
for (int i = 0; i < durationOfSimulation; i++) {
for (MobileObject obj : MoblieObjects) {
obj.move();
System.out.println("" + obj.getID() + " ( "
+ obj.getCurrentX() + ", " + obj.getCurrentY()
+ " )");
}
}
for (Geotask tsk : geotasks) {
tsk.printType();
}
} catch (FileNotFoundException e) {
System.out.println("Could not read the file");
}catch(NullPointerException e)
{
System.out.println("Null point exception");
}catch(IllegalArgumentException e)
{
System.out.println("Illegal Argument Exception");
}catch(IllegalStateException e)
{
System.out.println("Illegal State Exception");
}
}
}

Use
new InputStreamReader(Simulator.class.getResourceAsStream("Simulation.Configuration"));

You can return the directory of the program at run-time, which makes it OS independent.
System.out.printf("%s", System.getProperty("user.dir"));

Related

Why I get 'Resource leak: '<unassigned Closeable value>' ' error even when I use close() method in Java?

Why I get 'Resource leak: '' ' error even when I use close() method in Java?
I put the whole code and used comments where about where I get the error message and where I close the Scanner method.
I use Eclipse, Java 13.
Here's the code.
import java.util.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
public class VehicleTest {
public static void main(String[] args) {
VehicleTest vtest = new VehicleTest();
try {
vtest.menuLoop();
} catch(IOException e) {
System.out.println("IO Exception!");
System.exit(1);
} catch(CloneNotSupportedException e) {
System.out.println("CloneNotSupportedException");
System.exit(1);
}
}
private void menuLoop() throws IOException, CloneNotSupportedException {
Scanner scan = new Scanner(System.in);
ArrayList<Vehicle> arr=new ArrayList<Vehicle>();
Vehicle vehicle;
/** Deleted the hard coded adds so it doesn't add same types of cars
* everytime
*/
java.io.File file = new java.io.File("Vehicles.txt");
Scanner in = new Scanner(file).useLocale(Locale.US);
in.useDelimiter(","); //** This is where I get the resource leak error message **//
while (in.hasNext()) {
try {
String vehClass = in.next();
Class veh1 = Class.forName(vehClass);
Vehicle veh = (Vehicle)veh1.
getDeclaredConstructor().newInstance();
arr.add(veh);
veh.readData(in);
} catch (Exception e) {
System.out.print("Exception");
System.exit(0);
}
}
while(true) {
System.out.println("1...................................New car");
System.out.println("2...............................New bicycle");
System.out.println("3......................Find vehicle by name");
System.out.println("4..............Show data about all vehicles");
System.out.println("5.......Change direction of a given vehicle");
System.out.println("6.........................Test clone method");
System.out.println("7..................Test driveable interface");
System.out.println("8..............................Exit program");
System.out.println("...............................Your choice?");
int choice = scan.nextInt();
String name;
switch (choice) {
case 1:
arr.add(new Car());
vehicle = arr.get(arr.size() - 1);
try {
vehicle.setAllFields();
} catch(Exception e) {
System.out.println("Wrong input!");
System.exit(1);
}
break;
case 2:
arr.add(new Bicycle());
vehicle = arr.get(arr.size() - 1);
try {
vehicle.setAllFields();
} catch(Exception e) {
System.out.println("Wrong input!");
System.exit(1);
}
break;
case 3:
System.out.println("Name of vehicle: ");
name = scan.next();
for(Vehicle v : arr) {
if(v.getName() != null &&
(v.getName().compareToIgnoreCase(name) == 0)) {
System.out.println(v);
}
}
break;
case 4:
for(Vehicle v : arr) {
System.out.println(v);
}
break;
case 5:
System.out.println("Name of vehicle: ");
name = scan.next();
char dir;
int degree;
for(Vehicle v : arr) {
if(v.getName() != null &&
(v.getName().compareToIgnoreCase(name) == 0)) {
System.out.print("\nDirection [R/L]: ");
dir = scan.next().charAt(0);
System.out.print("\nDegrees [0-360]: ");
degree = scan.nextInt();
if (dir == 'L') { v.turnLeft(degree); }
if (dir == 'R') {v.turnRight(degree); }
}
}
break;
case 6:
Car car1 = new Car("A bad car","red",100000,1999,"A111",350,0);
Car car2 = (Car)car1.clone();
car2.getBuyingDate().set(2003, 1, 2);
car2.getProductionDate().set(2003, 5, 5);
System.out.println("Date objects are separate, deep copy");
System.out.printf("%n %tF", car1.getBuyingDate());
System.out.printf("%n %tF %n", car2.getBuyingDate());
System.out.printf("Production date car2 edited: "
+ "%n %tF %n", car2.getProductionDate());
break;
case 7:
Car carTest = new Car("Test car","red",100000,1999,
"A111",350,0);
Bicycle bicycleTest =
new Bicycle("Test bicycle","red",100000,
1999,"A111",15,0);
carTest.accelerate(3);
carTest.accelerate(250);
bicycleTest.accelerate(5);
bicycleTest.accelerate(200);
carTest.breaks(100);
bicycleTest.breaks(50);
carTest.stop();
bicycleTest.stop();
break;
case 8:
java.io.PrintWriter output = new java.io.PrintWriter(file);
for(Vehicle v : arr) {
v.writeData(output);
}
scan.close();
in.close(); //* **in.close() method is here**
output.close();
System.exit(0);
default:
System.out.println("Wrong input!");
}
}
}
}
Even when I put in.close() inside the try block, it still shows the same error.
And it still shows the same error even when I put in.close() right after.
Why is it that?
There are code paths where the resource is not closed. Either use a finally block, or a try-with-resources. Like,
try (Scanner in = new Scanner(file).useLocale(Locale.US)) {
in.useDelimiter(",");
while (in.hasNext()) {
try {
String vehClass = in.next();
Class veh1 = Class.forName(vehClass);
Vehicle veh = (Vehicle)veh1.
getDeclaredConstructor().newInstance();
arr.add(veh);
veh.readData(in);
} catch (Exception e) {
System.out.print("Exception");
System.exit(0);
}
}
}

How to make a quiz in java that plays a sound before each question?

I'm trying to make a quiz of musical chords in java and I need to program to play a sound file before asking each question although something is interfering halfway through.
I've tried to use an array list and fileInputStream player
here's some code I have tried.
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("eminor.mp3");
Player player = new Player(fileInputStream);
player.play();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch(JavaLayerException e) {
e.printStackTrace();
}
{
String question1 = "What chord is this?\n"
+ "(a)E minor\n(b)E major\n(c)C minor\n";
String question2 = "What chord is this?\n"
+ "(a)E Major\n(b)C major\n(c)G major\n";
String question3 = "What chord is this?\n"
+ "(a)E Major\n(b)C major\n(c)G major\n";
Question [] questions = {
new Question(question1,"a")
{;
}
};
Trial(questions);
}
}
public static void Trial(Question[] questions) {
int points = 0;
Scanner keyboardInput = new Scanner(System.in);
for(int i = 0; i< questions.length; i++) {
System.out.println(questions[i].prompt);
String answer = keyboardInput.nextLine();
if(answer.equals(questions[i].answer)) {
points++;}
else
System.out.println("Wrong Answer");
System.out.println(" Your score is " + ""+ points + "/" + questions.length);
System.out.println("Next Question");
try {
FileInputStream fileInputStream = new FileInputStream("gmajor.mp3");
Player player = new Player(fileInputStream);
player.play();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch(JavaLayerException e) {
e.printStackTrace();
}
}
}
public static void Trial2(Question[] questions) {
int points = 0;
Scanner keyboardInput = new Scanner(System.in);
for(int i = 0; i< questions.length; i++) {
System.out.println(questions[i].prompt);
String answer = keyboardInput.nextLine();
if(answer.equals(questions[i].answer)) {
points++;}
else
System.out.println("Wrong answer");
System.out.println("Your score is " + ""+ points + "/" + questions.length);
}
You should close your FileInputStream.close() or even better if you are using java 8 or greater use The try-with-resources Statement

code inside jButtonActionPerformed(ActionEvent e) method is not working

I have a jTextField, jLabel and a jButton. I want to set the jTextField to empty and update the jLabel to some new text after I perform jButton action.
This my code for jButtonActionPerformed(ActionEvent e) method:
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedWriter fw;
StringBuilder guessword = new StringBuilder(word);
try {
fw = new BufferedWriter(new FileWriter("C:\\Users\\Arihant\\JavaApplication1\\src\\javaapplication1\\scores.txt", true));
while(guesses != 0) {
jLabel26.setText(Integer.toString(guesses));
guesschar = jTextField2.getText().charAt(0);
flag = 0;
for(int j = 0; j < word.length() / 2; j++) {
if(Character.toLowerCase(guesschar) == temp[j] && (guessword.toString().indexOf(Character.toLowerCase(guesschar)) < 0)) {
flag = 1;
for(int k = 0; k < word.length(); k++) {
if(Character.toLowerCase(guesschar) == word.charAt(k))
guessword.setCharAt(k, Character.toLowerCase(guesschar));
}
if(guessword.toString().equals(word)) {
switch (difficulty) {
case "EASY":
points = guesses * 50;
break;
case "MODERATE":
points = guesses * 100;
break;
case "HARD":
points = guesses * 200;
break;
default:
points = 0;
break;
}
try {
fw.append(name + " " + points);
fw.newLine();
fw.close();
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
jPanel13.removeAll();
jPanel13.add(jPanel4);
jPanel13.repaint();
jPanel13.revalidate();
jLabel29.setText("<html>YOU WIN!<br/> The word was: </html>" + word);
jLabel31.setText("You scored: " + points + " points.");
jLabel28.setText("Play again?");
}
}
}
if(flag == 0) {
guesses--;
}
jPanel13.repaint();
jPanel13.revalidate();
jLabel1.setText(guessword.toString());
jTextField2.setText("");
Document document = jTextField2.getDocument();
document.addDocumentListener(new JButtonStateController(jButton8, 0));
((AbstractDocument) jTextField2.getDocument()).setDocumentFilter(new JTextFieldFilter(0));
}
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
When I click jButton8, it just skips the entire code in try-catch block and goes directly to jPanel13.removeAll();.
I want to set the jTextField2 to empty and jButton8 to disabled, each time I click jButton8.
Tell me, where I am wrong and how can I improve my code?

How to write main method for this code?

Okay following is my Simmulation.java file and I am supposed to write main method for it to work. But I have no idea how to do it.
I have tried like following, but it didn't work!
public static void main(String args[])
{
new Simmulation(args[0]);
}
Any help is much appreciated. Thank you in advance
This is my Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation
{
Queue < CashewPallet > inputQueue = new LinkedList < CashewPallet > ();
Stack < CashewPallet > stBay1 = new Stack < CashewPallet > ();
Stack < CashewPallet > stBay2 = new Stack < CashewPallet > ();
FileOutputStream fout4;
PrintWriter pw;
static int tick = 0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index = 0;
String nutType = "";
int id = 0;
Scanner s2;
try
{
sc = new Scanner(new File(fn));
fout4 = new FileOutputStream("nuts.txt");
pw = new PrintWriter(fout4, true);
String eol = System.getProperty("line.separator"); // Reading string line by line
while (sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if (s2.hasNext())
{
while (s2.hasNext())
{
String s = s2.next();
if (index == 0)
{
nutType = s;
}
else
{
id = Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype " + nutType + " Id is " + id + "tick " + tick);
if ((nutType.equalsIgnoreCase("A") || nutType.equalsIgnoreCase("P") || nutType.equalsIgnoreCase("C") || nutType.equalsIgnoreCase("W")) && id != 0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(), id));
System.out.println("Size of Queue " + inputQueue.size());
int k = 0;
if (!inputQueue.isEmpty())
{
while (inputQueue.size() > k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index = 0;
if (!stBay2.isEmpty())
{
while (!stBay2.isEmpty())
{
c1 = stBay2.pop();
temp = tick + " " + c1.getNutType() + " " + c1.getId() + eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp = tick + eol;
fout4.write(temp.getBytes());
}
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
closeStream();
}
public CashewPallet process(CashewPallet c)
{
// CashewPallet c=new CashewPallet();
int k = 0;
// while(stBay.size()>k)
// {
// c=stBay.pop();
String operation = c.getNutType();
if (c.getPriority() == 1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch (operation)
{
case "A":
shelling(c);
washing(c);
packing(c);
break;
case "C":
washing(c);
packing(c);
break;
case "W":
washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch (Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for " + c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for " + c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for " + c.getNutType());
}
stBay2.push(c);
return true;
}
The problem is that you are not passing any parameters to the program. So the length of the args is 0. What you can try is to check for the length of the args passed before using it.
if (args.length > 0)
new Simulation(args[0]);
else
new Simulation("Default value");
That should solve your problem.

Java Serialization issues

I have this code that writes an object:
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
And this code that loads the object:
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
I'm pretty sure that saving works, as when I opened the file in notepad++ I saw most of the data that I had saved, but when I load there is no data in module list.
Full source code:
import java.io.*;
import java.util.*;
public class Model implements java.io.Serializable {
private Student[] studentList = new Student[0];
private Module[] moduleList = new Module[0];
public void menu() {
while (true) {
System.out.println ("MENU");
System.out.println ("");
System.out.println (" 1 - Run Tests");
System.out.println (" 2 - Add Student");
System.out.println (" 3 - Add Module");
System.out.println (" 4 - Add Student To Module");
System.out.println (" 5 - Save System (Text file)");
System.out.println (" 6 - Load System (Text file)");
System.out.println (" 7 - Save System (Serialized)");
System.out.println (" 8 - Load System (Serialized)");
System.out.println (" 9 - Print Report");
System.out.println ("");
System.out.print ("Enter choice: ");
String input = keyboard.readString();
switch (input) {
case "1" :
runTests();
break;
case "2" :
System.out.print("First Name : ");
String fN = keyboard.readString();
System.out.print("Surname : ");
String sN = keyboard.readString();
System.out.print("Course Code : ");
String c = keyboard.readString();
System.out.print("User ID : ");
String iD = keyboard.readString();
AddStudent(iD, sN, fN, c);
break;
case "3" :
System.out.print("Module Code : ");
String code = keyboard.readString();
String[] temp = new String[0];
AddModule(code,temp);
break;
case "4" :
System.out.print("Module Code : ");
code = keyboard.readString();
Module m = findAModule(code);
if (m != null) {
System.out.print("User ID : ");
iD = keyboard.readString();
Student s = findAStudent(iD);
if (s != null) {
m.addThisStudent(s);
} else {
System.out.println("Student not found");
}
} else {
System.out.println("Module not found");
}
break;
case "5" :
saveToTextFiles();
break;
case "6" :
loadFromTextFiles();
break;
case "7" :
saveSerialized();
break;
case "8" :
break;
case "9" :
printReport();
break;
}
}
}
public void runTests() {
loadFromTextFiles();
saveSerialized();
printReport();
}
public void loadFromTextFiles() {
studentList = new Student[0];
moduleList = new Module[0];
try {
Scanner fileReader = new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String u = fileReader.nextLine();
String sn = fileReader.nextLine();
String fn = fileReader.nextLine();
String c = fileReader.nextLine();
AddStudent(u, sn, fn, c);
}
fileReader.close();
fileReader = new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String code = fileReader.nextLine();
int numOfStudents = fileReader.nextInt(); fileReader.nextLine();
String[] students = new String[numOfStudents];
for (int j = 0; j < numOfStudents; j++) {
students[j] = fileReader.nextLine();
}
AddModule(code, students);
}
fileReader.close();
} catch (IOException e) {}
}
public void saveToTextFiles () {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("students.txt")));
outfile.println(studentList.length);
for (int i = 0; i < studentList.length; i++) {
outfile.println(studentList[i].getUID());
outfile.println(studentList[i].getSN());
outfile.println(studentList[i].getFN());
outfile.println(studentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("modules.txt")));
outfile.println(moduleList.length);
for (int i = 0; i < moduleList.length; i++) {
outfile.println(moduleList[i].getCode());
outfile.println(moduleList[i].getStudents().length);
for (int j = 0; j < moduleList[i].getStudents().length; j++) {
outfile.println(moduleList[i].getStudents()[j]);
}
}
outfile.close();
} catch (IOException e) {}
}
public void saveSerialized() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
FileOutputStream fileOut2 = new FileOutputStream("Module.ser");
ObjectOutputStream out2 = new ObjectOutputStream(fileOut2);
out2.writeObject(studentList);
out2.close();
fileOut2.close();
FileOutputStream fileOut3 = new FileOutputStream("Student.ser");
ObjectOutputStream out3 = new ObjectOutputStream(fileOut3);
out3.writeObject(moduleList);
out3.close();
fileOut3.close();
} catch (IOException e) {}
}
public void loadSerialized() {
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
private Module[] getModuleList() {
return moduleList;
}
private Student[] getStudentList() {
return studentList;
}
private void setModuleList(Module[] m) {
moduleList = m.clone();
}
private void setStudentList(Student[] s) {
studentList = s.clone();
}
private void AddModule(String code, String[] students) {
int length = moduleList.length;
Module NewArray[] = new Module[length + 1];
for (int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Module(moduleList[i]);
}
}
NewArray[length] = new Module(code, students);
moduleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = studentList.length;
Student NewArray[] = new Student[length + 1];
for(int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Student(studentList[i]);
}
}
NewArray[length] = new Student(u, sn, fn, c);
studentList = NewArray.clone();
}
public void printReport() {
for (int i = 0; i < moduleList.length; i++) {
System.out.println(moduleList[i].toString(this));
}
}
public Student findAStudent(String uid) {
for (int i = 0; i < studentList.length; i++) {
if (studentList[i].getUID().compareTo(uid) == 0) {
return studentList[i];
}
}
return null;
}
public Module findAModule(String code) {
for (int i = 0; i < moduleList.length; i++) {
if (moduleList[i].getCode().compareTo(code) == 0) {
return moduleList[i];
}
}
return null;
}
}
Look at your code sample, in particular the switch statement:
switch (input) {
...
case "8" :
break;
...
}
I'd assume the method loadSerialized should be called there but it's missing and is not called anywhere else in the code.
Once you actually call the method that does the loading, the code will work, assuming you have declared a serialVersionUID for both Student and Module.
Edit: why using serialization to persist objects is a bad idea
In simple terms, using serialization to persist objects is brittle.
An object's serialized form is tied to its class. Classes tend to change over time, meaning the serialized instance of the old cannot be loaded into the new.
While you can work round this by setting a serialVersionUID doing so introduces a reverse of the problem where, in the case new fields are introduced, the new cannot be read into objects of the old class, which can be a problem if you do rolling updates to the deployed system.
There's a host of other reasons - it's not easily readable (meaning you can't update it like you would a database or XML/JSON doc), it's inefficient, etc.

Categories