Code Comments
Programming Forum and web based access to our favorite programming groups.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!
Post Follow-up to this message
"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
Post Follow-up to this messageOn 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
Post Follow-up to this message
"Steven" wrote...
> "BladeZ" <cockjupp@hotmail.com> wrote:
> 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
Post Follow-up to this messageOn 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 t
o
>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;
}
}
}
Post Follow-up to this messageThanks 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
Post Follow-up to this messageOn 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
Post Follow-up to this message"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
Post Follow-up to this messageOk 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!
Post Follow-up to this message
"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
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.