Home > Archive > Java Help > April 2005 > Saving and Opening an Array List
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Saving and Opening an Array List
|
|
| BladeZ 2005-04-24, 8:57 am |
| Hello,
I've recently begun to look at Array Lists, I know some of the basic
methods that you can do such as clear(), remove() and add().
However now I would like to be able to Save an Array List to a .txt file,
and then open it from the .txt file.
I'm quite new to Java and also not very good at it, so I can't really
think how it could be done. Maybe just a loop or something that writes in
an array list entry to the .txt file and then creates a new line. But I'm
not sure to even start that. I'm having a lot of trouble reading text from
an Array List entry and placing it in a text field.
Any help is welcome, example code would be much appriciated.
Thanks a lot in advance!
| |
| Bjorn Abelli 2005-04-24, 3:57 pm |
|
"BladeZ" wrote...
> However now I would like to be able to Save an Array List
> to a .txt file, and then open it from the .txt file.
You don't want to save an ArrayList to a text file. Possibly you would want
to save the *content* of the *objects* from an ArrayList.
An ArrayList is just a container for objects, so what you should start with
is to learn how to write and read the contents of a singular object first.
If your ArrayList only contains objects of type String, it's quite simple.
----
PrintWriter out = null;
String filename = "mytextfile.txt";
// Open the file for writing...
try
{
FileOutputStream ostream =
new FileOutputStream(filename);
out = new PrintWriter(ostream);
}
catch (Exception ee)
{
System.err.println(ee);
}
// Here you can write the text in a form that you later
// can read and "translate" into objects again.
// When you have figured this out, you can put the following
// statement into a loop
out.println("Whatever String you want to write");
// Don't forget to close the file...
out.close();
----
The reading of the text file follows the same pattern.
----
BufferedReader in = null;
String result = null;
// Open the file for reading
try
{
in = new BufferedReader(new FileReader(filename));
}
catch (FileNotFoundException ee)
{
System.err.println(ee);
}
// Here you simply read a line at the time
// for a slong you need to read it, a.k.a.
// this block could be inside a loop
try
{
result = in.readLine();
if (result == null)
{
// Here you have reached the end of the file, so you
// should make your way out of the reading here...
}
}
catch (Exception e)
{
System.out.println(e);
}
// Don't forget to close the file...
try
{
in.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
----
> I'm quite new to Java and also not very good at it, so I can't
> really think how it could be done. Maybe just a loop or something
> that writes in an array list entry to the .txt file and then
> creates a new line. But I'm not sure to even start that.
As I said above, start with the single object, and then you can do the
writing inside an iteration, for each object.
> I'm having a lot of trouble reading text from
> an Array List entry and placing it in a text field.
And it's from this statement I believe that you're storing other objects
than just Strings in you ArrayList.
Figure out how you can "translate" that object into a comprehensible String,
before you try to write it to a text file.
Hint: What are the attributes of the object?
// Bjorn A
| |
| Steven 2005-04-24, 3:57 pm |
| On Sun, 24 Apr 2005 06:37:33 -0400, "BladeZ" <cockjupp@hotmail.com>
wrote:
>Hello,
>
>I've recently begun to look at Array Lists, I know some of the basic
>methods that you can do such as clear(), remove() and add().
>
>However now I would like to be able to Save an Array List to a .txt file,
>and then open it from the .txt file.
>
>I'm quite new to Java and also not very good at it, so I can't really
>think how it could be done. Maybe just a loop or something that writes in
>an array list entry to the .txt file and then creates a new line. But I'm
>not sure to even start that. I'm having a lot of trouble reading text from
>an Array List entry and placing it in a text field.
>
>Any help is welcome, example code would be much appriciated.
>
>Thanks a lot in advance!
The ArrayList is serializable, so you should be able to do the
following:
ArrayList AL = new ArrayList();
FileOutputStream fos = new FileOutputStream("out.file.name");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(AL);
oos.close();
I am not sure, but I assume the objects contained in the ArrayList
need to be serializable as well for it to work.
--Steve
| |
| Bjorn Abelli 2005-04-24, 3:57 pm |
|
"Steven" wrote...
> "BladeZ" <cockjupp@hotmail.com> wrote:
[color=darkred]
> The ArrayList is serializable, so you should be able to do the
> following:
>
> ArrayList AL = new ArrayList();
>
> FileOutputStream fos = new FileOutputStream("out.file.name");
> ObjectOutputStream oos = new ObjectOutputStream(fos);
> oos.writeObject(AL);
> oos.close();
Just to clarify a small thing. The code above will need to be in a
try-catch-block...
> I am not sure, but I assume the objects contained in the ArrayList
> need to be serializable as well for it to work.
That's correct.
And to read it from that file, including the contained objects, it's just to
do:
FileInputStream in = new FileInputStream("out.file.name");
ObjectInputStream oin = new ObjectInputStream(in);
ArrayList a2 = (ArrayList) oin.readObject();
oin.close();
....also inside a try-catch-block...
However, I believe the OP wanted to write it in "text form".
The contents of the file above will not be humanly readable with e.g.
Notepad or other text tools...
// Bjorn A
| |
| Steven 2005-04-24, 3:57 pm |
| On Sun, 24 Apr 2005 15:19:07 +0200, "Bjorn Abelli"
<bjorn_abelli@DoNotSpam.hotmail.com> wrote:
>
>"Steven" wrote...
>
>
>
>Just to clarify a small thing. The code above will need to be in a
>try-catch-block...
>
>
>That's correct.
>
>And to read it from that file, including the contained objects, it's just to
>do:
>
> FileInputStream in = new FileInputStream("out.file.name");
> ObjectInputStream oin = new ObjectInputStream(in);
> ArrayList a2 = (ArrayList) oin.readObject();
> oin.close();
>
>...also inside a try-catch-block...
>
>However, I believe the OP wanted to write it in "text form".
>
>The contents of the file above will not be humanly readable with e.g.
>Notepad or other text tools...
>
>
>// Bjorn A
>
Good catch, I missed the .txt, I just assumed that the OP wanted it to
go to an output file. If I were doing this myself I would write it out
as an XML file unless I had a good reason to serialize it or do a text
file.
Just to finalize my thought I wrote a quick and dirty peice of code
that does what I suggested with serialization; just in case the OP
didn't care to read it.
--Steve
package test;
import java.io.Serializable;
public class ArrayListEntry implements Serializable {
private static final long serialVersionUID = 1L;
private String data = null;
public ArrayListEntry(String s)
{
data = s;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public boolean equals(Object o)
{
if (o.getClass()==ArrayListEntry.class)
{
return this.equals((ArrayListEntry)o);
}
return false;
}
public boolean equals(ArrayListEntry o)
{
return o.getData().equals(this.data);
}
}
package test;
import java.util.*;
import java.io.*;
public class ArrayListTest {
public static final String file = "C:\\out.test";
public static void main(String[] args) {
ArrayList<ArrayListEntry> test1 = new
ArrayList<ArrayListEntry>();
test1.add(new ArrayListEntry("one"));
test1.add(new ArrayListEntry("two"));
test1.add(new ArrayListEntry("three"));
writeArrayList(test1);
ArrayList<ArrayListEntry> test2 = readArrayList();
if (test1.containsAll(test2))
{
System.out.println("All's well");
}
else
{
System.out.println("Error");
}
}
public static void writeArrayList(ArrayList<ArrayListEntry> a)
{
try {
FileOutputStream fos = new
FileOutputStream(file);
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static ArrayList<ArrayListEntry> readArrayList()
{
try {
FileInputStream fis = new
FileInputStream(file);
ObjectInputStream ois = new
ObjectInputStream(fis);
ArrayList<ArrayListEntry> a =
(ArrayList<ArrayListEntry> )ois.readObject();
ois.close();
return a;
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
}
| |
| BladeZ 2005-04-24, 3:57 pm |
| Thanks for the help Bjorn and Steve, I don't understand everything of what
you've shown me.
I think I should give you some more information about what I need to do
overall.
I need to create a 'bookshop' application, where there are two text
fields. One for name of the book and the other for the Author. I then need
to display all of the info for a book (name and author) in a string.
The basics I understand but its just I also need to save the array list of
all the book info and open it aswell, which is what I've asked for help. I
also forgot to mention I need to use a FileDialog for the saving and
opening (do i need to do anything different then?). Also I am doing OO
programming (does that make a difference aswell?)
This is all part of my Java project at University. The reading an array
stiring into a Text filed was for a exercise we did when we where first
introduced to Array Lists, we had to creat a cut effect, which removes an
entry from the array list but places the string that waas in it into a
text field ready to be used to name another entry into the array list.
I think the stuff you've given me is maybe a little advanced for my level,
I've never seen
FileOutputStream ostream =
new FileOutputStream(filename);
before, or maybe I just wasn't paying enough attention.
I'll have a closer look at my notes and talk to my fellow students, also
my lecturer, all they showed us was how to very bascially save a txt file
and how to make an array list and now they expect us to save an array
list?
Anyway, thank you again Bjorn and Steve, I'll post again if I'm still
having a lot of trouble.
Thanks
| |
| Steven 2005-04-24, 3:57 pm |
| On Sun, 24 Apr 2005 10:05:57 -0400, "BladeZ" <cockjupp@hotmail.com>
wrote:
>Thanks for the help Bjorn and Steve, I don't understand everything of what
>you've shown me.
>
>I think I should give you some more information about what I need to do
>overall.
>
>I need to create a 'bookshop' application, where there are two text
>fields. One for name of the book and the other for the Author. I then need
>to display all of the info for a book (name and author) in a string.
>
>The basics I understand but its just I also need to save the array list of
>all the book info and open it aswell, which is what I've asked for help. I
>also forgot to mention I need to use a FileDialog for the saving and
>opening (do i need to do anything different then?). Also I am doing OO
>programming (does that make a difference aswell?)
The file dialog included in the API takes care of most of the work,
you just need to use it to get the file name to use. It should not
change either of our approaches much to handle it. As for being OOP we
didn't use any fancy patterns for this merely created a class for the
entries and used a canned ArrayList. Still OOP.
>
>This is all part of my Java project at University. The reading an array
>stiring into a Text filed was for a exercise we did when we where first
>introduced to Array Lists, we had to creat a cut effect, which removes an
>entry from the array list but places the string that waas in it into a
>text field ready to be used to name another entry into the array list.
>
>I think the stuff you've given me is maybe a little advanced for my level,
>I've never seen
>
>FileOutputStream ostream =
> new FileOutputStream(filename);
>
>before, or maybe I just wasn't paying enough attention.
>
>I'll have a closer look at my notes and talk to my fellow students, also
>my lecturer, all they showed us was how to very bascially save a txt file
>and how to make an array list and now they expect us to save an array
>list?
>
>Anyway, thank you again Bjorn and Steve, I'll post again if I'm still
>having a lot of trouble.
Let me just emphasize what Bjorn said. Concentrate on getting your
class entry save mechanism working then work on writing the whole
ArrayList out to the file. I bet they didn't intend you to do what I
suggested. Good luck with the project.
>
>Thanks
| |
| Bjorn Abelli 2005-04-24, 3:57 pm |
|
"BladeZ" wrote...
> I need to create a 'bookshop' application, where there are
> two text fields. One for name of the book and the other for
> the Author. I then need to display all of the info for a book
> (name and author) in a string.
That has nothing to do with saving the objects to a file.
I think you should start to get that part working first, and worry about how
to write/read the objects from file after that.
> The basics I understand but its just I also need to save the
> array list of all the book info and open it aswell, which is
> what I've asked for help. I also forgot to mention I need to
> use a FileDialog for the saving and opening (do i need to do
> anything different then?).
My suggestion would be to skip the "FileDialog" part until you've got the
write/read-part of your assignment working.
> Also I am doing OO
> programming (does that make a difference aswell?)
Not really. There are even more possible ways to store your objects, where
the two forms Steven and I suggested IMHO really aren't the ones most used
in practice. In reality the objects will be stored in some persistent state
in a database of some sort, but that's another story... ;-)
Possibly you've misunderstood your teacher's directions?
Even though the "Book" objects contain two text fields, that doesn't
necessarily imply that the objects must be stored as text...
> This is all part of my Java project at University. The reading an array
> stiring into a Text filed was for a exercise we did when we where first
> introduced to Array Lists, we had to creat a cut effect, which removes an
> entry from the array list but places the string that waas in it into a
> text field ready to be used to name another entry into the array list.
>
> I think the stuff you've given me is maybe a little advanced for my level,
> I've never seen
>
> FileOutputStream ostream =
> new FileOutputStream(filename);
>
> before, or maybe I just wasn't paying enough attention.
Most likely.
If your assignment includes the saving of the objects to a file (whether in
text or serialized form) your teacher would most definitely have gone
through some of the classes in the java.io-package, or at least have told
you to look it up somehow.
So my suggestions in short:
1. Start with the "bookshop" application, where
you can display some Books in a proper way.
2. Add the functionality to save the objects (Books),
but start with a specific filename, and don't
bother with FileDialog, until you've got the
"saving" and "restoring" working.
If your teacher don't mind, save them in serialized form, in the way Steven
suggested. That simplifies things much, as you can save the ArrayList as a
whole. Dont forget to make your Book class implement the interface
Serializable then.
3. Add the FileDialog, where your "static" filename
will be exchanged for the one you're getting with
FileDialog.
// Bjorn A
| |
| BladeZ 2005-04-25, 8:59 am |
| Ok guys I spoke to my lecturer today and this is what he said.
------------------------
The data (title and author) of a book should be stored in an object of a
Book class that
you need to define and the list of books should be stored in an array list
(B&P pp243-
248), not an array. It should be possible to save this list of books to a
file and, because
the user chooses a name for the file, it should be possible to store
different lists of books
in different files.
Whole objects can be saved to file in Java using what is known as object
serialization, but
we haven't covered that (and it's not in B&P) so it's probably better to
save the data to a
text file. The title and author are intended to be separate attributes of
the Book object so
it would be possible to store them in just one line of the file if you
used, for example, the
StringTokenizer class (B&P p287-288). Alternatively, you could, for
example, store the
title and author on alternate lines:
title of first book
author of first book
title of second book
author of second book
etc.
-----------------------------
As you can see he mentioned serialization as you suggested but obviously
we havent covered it yet.
He also mentioned possibly using a StringTokenizer however the opening of
the file and reading it into an array list would be quite difficult.
So i'll go for the option that he suggested which is to save everything on
a different line. IF you could just confirm how the structure should go.
Read the author and place in first line;
Read name and place in second line;
Loop the process;
I think though the looping might not be so straight forward because of the
two lines, i'm not sure how the loop would look like.
So now I see I have two obstacles to overcome, reading a string from an
array and placing it into a .txt file (still haven't been able to do it to
a textField although i haven't tried it so much) and then creating a loop
which will place everything on a different line and still be in order.
Again, any advice is welcome and good advice! Even though it may not help
me out now it probably will sometime or other.
Thanks again!
| |
| Bjorn Abelli 2005-04-26, 9:00 am |
|
"BladeZ" wrote...
> The data (title and author) of a book should be stored in
> an object of a Book class that you need to define and the
> list of books should be stored in an array list (B&P pp243-
> 248), not an array.
So you need to define a Book class, with at least a constructor and
accessors (get-methods) for the title and author.
Instances of the Book class is as easily stored in and retrieved from an
ArrayList as instances of String:
ArrayList a1 = new ArrayList();
Book book = new Book("Hitchhikers guide", "Adams");
a1.add(book);
book = new Book("Thinking in Java", "Eckel");
a1.add(book);
...
Book b2 = (Book) a1.get(0); // Retrieve a Book from ArrayList
String t = b2.getTitle(); // Retrieve the title from book
String a = b2.getAuthor(); // Retrieve the author from book
> He also mentioned possibly using a StringTokenizer however
> the opening of the file and reading it into an array list
> would be quite difficult.
I don't think he meant you to read in the whole file and split it that way,
but to arrange the attributes of each book in a way so you could write each
Book on one line, and when reading split *that* into the title and author
fields with a StringTokenizer.
Anyway, if you're uncomfortable with StringTokenizer, just do it the way he
suggested, with each field on a line of its own.
> So i'll go for the option that he suggested which is to save
> everything on a different line. IF you could just confirm how
> the structure should go.
>
> Read the author and place in first line;
> Read name and place in second line;
> Loop the process;
I don't understand what you mean by "place" here...
Think about it, how would the text file look like when you have written all
books into it?
Hitchhikers guide
Adams
Thinking in Java
Eckel
Hence, each book is occupying two lines, *always* two lines, always
following each other...
> I think though the looping might not be so straight forward
> because of the two lines, i'm not sure how the loop would
> look like.
Just like any other loop, but with *two* "reads" from the file for each Book
(each loop), one for the title, one for the author.
> So now I see I have two obstacles to overcome, reading
> a string from an array and placing it into a .txt file
> (still haven't been able to do it to a textField although
> i haven't tried it so much)
See my example above...
> and then creating a loop which will place everything
> on a different line and still be in order.
You should be able to figure out how to do a simple iteration through an
ArrayList, just by looking at the examples in your course book.
To write it to a text file, you can simply follow the first example I gave
you in this thread.
// Bjorn A
| |
| Steven 2005-04-26, 4:02 pm |
| Bjorn, you are more helpful than I am. Once he mentioned that it was a
school assignment I took more hands off approach. I fugured that I did
too much already. I hope we didn't give him too much help. ;-)
--Steve
| |
| Bjorn Abelli 2005-04-26, 4:02 pm |
|
"Steven" wrote...
> Bjorn, you are more helpful than I am. Once he mentioned
> that it was a school assignment I took more hands off
> approach. I fugured that I did too much already. I hope
> we didn't give him too much help. ;-)
I don't think so... ;-)
We only provided bits and pieces, that can work as "building blocks" in his
assignment.
The difficult part in learning programming, isn't really those bits and
pieces, but to understand how to use them.
If he can put them together in a workable manner, then he have shown that he
can handle (at least some of) the part of programming that is more important
than syntax; algorithmic thinking and logic.
// Bjorn A
| |
| Steven 2005-04-26, 4:02 pm |
|
>
>"Steven" wrote...
>
>
>I don't think so... ;-)
>
>We only provided bits and pieces, that can work as "building blocks" in his
>assignment.
>
>The difficult part in learning programming, isn't really those bits and
>pieces, but to understand how to use them.
>
>If he can put them together in a workable manner, then he have shown that he
>can handle (at least some of) the part of programming that is more important
>than syntax; algorithmic thinking and logic.
Well I see you were another lucky recipient of a homework assignment.
Apparently we made an impact on this topic. :-)
--Steve
| |
| BladeZ 2005-04-27, 4:01 pm |
| Hey Bjorn and Steve,
I still cant get the reading from array to text field working.
I looked through the book I have (Bell & PArr Java for Students) and I
found this piece of code which should've got it working.
---------
private void cut() {
if (itemSelected)
text = (String)artists.get(indexSelected); //This last piece of
code is what the book gave me
--------------
And my program compiles, but when i run it and do the action that uses the
cut method i get a "java.lang.ClassCastException" thrown at me.
I've breifly covered exception, but I haven't come across this before and
cant even figure out what it could mean.
It refers to the code that i got from the book (think it means the String
part)
This isn't related to the Book program I'm trying to do, this is to do
with a little class exercise that I'm trying to develop further so my end
project can be better.
Any ideas?
Here are some notes on my code;
So you know 'text' is a String I declared that gets text from the
TextField. I've also used it here for example;
-----
artist = new Artist(text);
artists.add(artist);
-----
That adds a new 'Artist'(Artist is a class, not the main one. It has a
constructor in it which creates an 'artist', well the visual aspects of it
at least.) to the array list 'artists'.
Can you help me out a little more?
| |
| Steven 2005-04-27, 8:59 pm |
| >Hey Bjorn and Steve,
>
>I still cant get the reading from array to text field working.
>
>I looked through the book I have (Bell & PArr Java for Students) and I
>found this piece of code which should've got it working.
>
>---------
>private void cut() {
> if (itemSelected)
> text = (String)artists.get(indexSelected); //This last piece of
>code is what the book gave me
>--------------
>
>And my program compiles, but when i run it and do the action that uses the
>cut method i get a "java.lang.ClassCastException" thrown at me.
>
I am not too sure what is going on since artists is not a standard
class. It would appear that artists.get(indexSelected) is not
returning a String. What does artists.get(..) return ?
--Steve
|
|
|
|
|