Cannot be cast to java.util.ArrayList - java

Trying to write an object to an array and then save to output.data, then read the objects again.
Writing:
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(arr);
JOptionPane.showMessageDialog(null, "File Written Successfully");
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Reading:
private void readBtnActionPerformed(java.awt.event.ActionEvent evt) {
File inFile;
FileInputStream fStream;
ObjectInputStream oStream;
try {
inFile = new File("output.data");
fStream = new FileInputStream(inFile);
oStream = new ObjectInputStream(fStream);
//create an array of assessments
ArrayList <Assessment> xList;
xList = (ArrayList<Assessment>)oStream.readObject();
for (Assessment x:xList) {
JOptionPane.showMessageDialog(null, "Name: " + x.getName() + "Type: " + x.getType() + "Weighting: " + x.getWeighting());
}
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
} catch (ClassNotFoundException ex) {
System.out.println("Error: " + ex);
}
}
The code comppiles just fine, and the file itself saves alright too. But when I try to read the file nothing happens, and NetBeans says
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Lnetbeansswingexample.Assessment; cannot be cast to java.util.ArrayList"
the line of code giving trouble seems to be
xList = (ArrayList<Assessment>)oStream.readObject();
Any help would be really appreciated, thanks. Sorry if the answers obvious, pretty new to programming.

Based on the exception you got, it looks like oStream.readObject() returns an array of Assessment, not a List. You can convert it to a List:
List <Assessment> xList;
xList = Arrays.asList((Assessment[])oStream.readObject());
or if you must use a java.util.ArrayList :
ArrayList<Assessment> xList;
xList = new ArrayList<> (Arrays.asList((Assessment[])oStream.readObject()));

Related

Change ArrayList from an Object to more specific type

Is it possible to change the object type of an array list i.e. from an Object ArrayList to a specific object ArrayList. I have tried using a for each. Alternatively is there a way to change the filehandling method such that it can return a specific type depending on which file it reads from without duplicating code?
My Attempt:
ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add(addType);
}
getLibrarianRecords code
public static ArrayList<Object> getLibrarianRecords(String filename){
ArrayList<Object> fromFile = new ArrayList<>(); //Array of
// existing librarians
try{
FileInputStream fIS =
new FileInputStream(SYSTEM_PATH + filename);
ObjectInputStream oIS = new ObjectInputStream(fIS);
fromFile = (ArrayList<Object>)oIS.readObject();
} catch (IOException ex){
System.out.println("Failed to read from file " + ex.getMessage());
ex.printStackTrace(); //Catches an IO exception.
} catch (ClassNotFoundException ex){
System.out.println("Error class not found" + ex.getMessage());
ex.printStackTrace(); //Catches a class not found
// exception.
}
return fromFile; //Returns the array list.
}
It is rarely a good idea to read objects from a file like this. That said all you really need to do is to cast the result of oIS.readObject() to an ArrayList<Librarian> instead of carrying it to ArrayList<Object> (as you do now) and then amend the return type of getLibrarianRecords. Oh, and naturally also the type of the local variable fromFile.
public static ArrayList<Librarian> getLibrarianRecords(String filename){
ArrayList<Librarian> fromFile = new ArrayList<>(); //Array of
// existing librarians
try{
FileInputStream fIS =
new FileInputStream(SYSTEM_PATH + filename);
ObjectInputStream oIS = new ObjectInputStream(fIS);
fromFile = (ArrayList<Librarian>)oIS.readObject();
} catch (IOException ex){
System.out.println("Failed to read from file " + ex.getMessage());
ex.printStackTrace(); //Catches an IO exception.
} catch (ClassNotFoundException ex){
System.out.println("Error class not found" + ex.getMessage());
ex.printStackTrace(); //Catches a class not found
// exception.
}
return fromFile; //Returns the array list.
}
There should then be no need to loop over the list to actually do the type conversion on an element by element basis.
Thanks to #user3170251 for suggesting casting
ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add((Librarian) addType);
}
For changing the type this does work.
You can use this generic class definition
class ArrayListConverter<T> {
List<T> cast;
public ArrayListConverter(List<T> typeList){
cast = new ArrayList<>();
for (Object addType: typeList) {
cast.add((T)addType);
}
}
public List<T> getList(){
return cast;
}
}
Just do this:
ArrayListConverter<Librarian> conv = new ArrayListConverter<>(libList);
ArrayList<Librarian> libListOg = conv.getList();

Java too many open files exception

I have a problem on my code; basically I have an array containing some key:
String[] ComputerScience = { "A", "B", "C", "D" };
And so on, containing 40 entries.
My code reads 900 pdf from 40 folder corresponding to each element of ComputerScience, manipulates the extracted text and stores the output in a file named A.txt , B.txt, ecc ...
Each folder "A", "B", ecc contains 900 pdf.
After a lot of documents, an exception "Too many open files" is thrown.
I'm supposing that I am correctly closing files handler.
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader = new FileReader(dizionario);
} catch (FileNotFoundException e) { }
try {
BufferedReader bufferedReader = new BufferedReader(fileReader);
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (! line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else { System.err.println("Dictionary file not found."); }
bufferedReader.close();
fileReader.close();
fileWriter.close();
} catch (IOException e) { return false;}
catch (NullPointerException ex ) { return false;}
finally {
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
But the error still comes. ( it is thrown at:)
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
Thank you.
EDIT: SOLVED
I found the solution, there was, in the main function in which writeOccurencesFile is called, another function that create a RandomAccessFile and doesn't close it.
The debugger sais that Exception has thrown in writeOccurencesFile but using Java Leak Detector i found out that the pdf were already opened and not close after parsing to pure text.
Thank you!
Try using this utility specifically designed for the purpose.
This Java agent is a utility that keeps track of where/when/who opened files in your JVM. You can have the agent trace these operations to find out about the access pattern or handle leaks, and dump the list of currently open files and where/when/who opened them.
When the exception occurs, this agent will dump the list, allowing you to find out where a large number of file descriptors are in use.
i have tried using try-with resources; but the problem remains.
Also running in system macos built-in console print out a FileNotFound exception at the line of FileWriter fileWriter = ...
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
try (FileWriter fileWriter = new FileWriter( "files/" + categoria + ".txt" , true)) {
try (FileReader fileReader = new FileReader(dizionario)) {
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (!line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else {
System.err.println("Dictionary file not found.");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
This is the code that i am using now, although the bad managing of Exception, why the files seem to be not closed?
Now i am making a test with File Leak Detector
Maybe your code raises another exception that you are not handling. Try add catch (Exception e) before finally block
You also can move BufferedReader declaration out the try and close it in finally

JAVA - trouble with loading a object based file

i am having a little trouble reading a object from a text file as it preduces the following error;
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to stock.control.system.StockItem
which is this line;
StockItem result = (StockItem) ois.readObject();
below is how i save my file;
try { FileOutputStream fout = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(StockItems); }
catch (java.io.FileNotFoundException error) {
System.out.println("FILE NOT FOUND!");
}
and here is what i have done for far for loading the file back into a object ArrayList;
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("LOADING DATA ...");
StockItem result = (StockItem) ois.readObject();
ois.close();
System.out.println(result.getItemID() + ", " + result.getItemDesc()
+ ", " + result.getPrice() + ", " + result.getQuantity() + ", "
+ result.getReOrderLevel()); // used for testing
} catch (java.io.FileNotFoundException error) {
System.out.println("FILE NOT FOUND!");
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(StockArrayList.class.getName()).log(Level.SEVERE, null, ex);
}
if anywhere could educate me so it can be done correctly it would be much appreciated.
The error says that what was written to the file is an ArrayList.
Looks like that StockItems you write is ArrayList<StockItem>. When you read, you get the array list back, so you can't cast it to StockItem. You need to cast it to ArrayList and then iterate over the list and cast each element to StockItem.
Looks like the file does not contain what you think it does. It contains an ArrayList, not a StockItem. Try taking the first element of the arraylist:
StockItem result = (StockItem) ((ArrayList)ois.readObject()).get(0)
and see what type that is.
I just had to assign the output to a array list in a tester class which was then in turn fed into a interface and from within the interface i had to assign it into another array list, this was how i fixed this error.

How to deserialize multiple objects from file

How do I deserialize multiple objects from a file? Following is code that I have tried which works fine for one object but not for multiple objects.
public List<Show> populateDataFromFile(String fileName) {
// TODO Auto-generated method stub
Show s = null;
//FileInputStream fileIn=null;
try
{
FileInputStream fileIn=new FileInputStream("C:\\Users\\Admin\\Desktop\\Participant_Workspace\\Q1\\ShowBookingSystem\\ShowDetails.ser");
int i=0;
while((i=fileIn.read())!=-1){
// fileIn = new FileInputStream("C:\\Users\\Admin\\Desktop\\Participant_Workspace\\Q1\\ShowBookingSystem\\ShowDetails.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
s = (Show) in.readObject();
in.close();
fileIn.close();
System.out.println("Name: " + s.getShowName());
System.out.println("Show Time: " + s.getShowTime());
System.out.println("Seats Available: " + s.getSeatsAvailable());
}
}catch(IOException i)
{
i.printStackTrace();
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
}
return null;
}
I even tried using
while((i=fin.read())!=-1)
but it did not work. What change do I need to make?
Try this way:
Show s = null;
try {
FileInputStream fileIn = new FileInputStream(".....");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (true) {
try {
s = (Show) in.readObject();
} catch (IOException ex) {
break;
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Name: " + s.getShowName());
System.out.println("Show Time: " + s.getShowTime());
System.out.println("Seats Available: " + s.getSeatsAvailable());
}
in.close();
fileIn.close();
Below is a short working example. You will need to remove the ObjectInputStream in = new ObjectInputStream(fileIn); from outside the while loop as well.
FileInputStream fis = new FileInputStream("...");
ObjectInputStream ois = new ObjectInputStream(fis); //<- Outside the while loop.
try
{
while(true)
{
Student std = (Student)ois.readObject();
System.out.println(std.getName());
System.out.println(std.getAge());
}
}
catch(IOException e)
{
e.printStackTrace(); //This exception will be thrown if the End Of File (EOF) is reached.
//
}
finally
{
fis.close(); //<- Outside the while loop.
ois.close(); //<- Outside the while loop.
}
In this case the solution is:
to put all objects in a list
serialize the list
This way you only have one object to de-serialize: the list. (As a bonus you get your object in a nicely organised (or not!) list).
If you have multiples type of object to serialize, serialize them in a list per class. Each list in a different file.

writing to text file multiple times android

i using this function:
> private void writeToFile(String data) {
> try {
> OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("mywords.txt",
> Context.MODE_PRIVATE));
> outputStreamWriter.write(data);
> outputStreamWriter.close();
> }
> catch (IOException e) {
> Log.e("Exception", "File write failed: " + e.toString());
> } }
i want to write a lot of times and every time i write it changes like deletes all and adds new thing i write but i do not want it to delete
husky thanks i do not know why you deleted your comment it works i changed to MODE_APPEND
another problem how do i do space in the text file
Pass true as the second argument to FileOutputStream to open the file in append mode.
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("mywords.txt", true), "UTF-8");
OutputStreamWriter by default overwrites. In order to append information to a file, you will have to give it additional information in the constructor. See also OutputStreamWriter does not append for more information.
Try this:
private void writeToFile(String data) {
File file = new File("mywords.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, true);
// Writes bytes from the specified byte array to this file output stream
fos.write(data.getBytes());
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while writing file " + ioe);
}
finally {
// close the streams using close method
try {
if (fos != null) {
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}

Categories

Resources