Hey C.C !!
I was wondering is it possible to save an entire ArrayList and later read it so it can be use able again?
I haven't found any reliable sources, so I am wondering, could anyone show me how it is performed?
Thanks in advance :)
Need help with ArrayList...
Started by Turk4n, Dec 03 2008 12:22 AM
4 replies to this topic
#1
Posted 03 December 2008 - 12:22 AM
|
|
|
#2
Posted 03 December 2008 - 03:22 AM
Sure, why don't you save the array list to a file, and then read it later? Read the stuff into an array list, do whatever you want to with it. Then when you're done with the array list just print it back to the file. :)
public static void main(String[] args) throws IOException {
Scanner sin = new Scanner(new FileReader("DATA.txt"));
ArrayList<Integer> arnNums = new ArrayList<Integer>();
// read the items into the array list
while (sin.hasNextInt()) {
/**
* as long as the file has another integer to read
* add it to the array list
*/
arnNums.add(sin.nextInt());
}
// print them to a file
PrintWriter fout = new PrintWriter(new FileWriter("DATA.txt"));
for (int index=0;index<arnNums.size();index++) {
fout.println(arnNums.get(index)); // get the value at the current index and print it to the file
}
sin.close();
fout.close();
}
#3
Posted 03 December 2008 - 04:44 AM
chili5 said:
Sure, why don't you save the array list to a file, and then read it later? Read the stuff into an array list, do whatever you want to with it. Then when you're done with the array list just print it back to the file. :)
public static void main(String[] args) throws IOException {
Scanner sin = new Scanner(new FileReader("DATA.txt"));
ArrayList<Integer> arnNums = new ArrayList<Integer>();
// read the items into the array list
while (sin.hasNextInt()) {
/**
* as long as the file has another integer to read
* add it to the array list
*/
arnNums.add(sin.nextInt());
}
// print them to a file
PrintWriter fout = new PrintWriter(new FileWriter("DATA.txt"));
for (int index=0;index<arnNums.size();index++) {
fout.println(arnNums.get(index)); // get the value at the current index and print it to the file
}
sin.close();
fout.close();
}
I will try out in meanwhile thanks for giving me a small demo of it :D
#4
Posted 03 December 2008 - 09:51 AM
Yeah it'll work with an array list of any data type. :)
#5
Posted 03 December 2008 - 10:14 AM
chili5 said:
Yeah it'll work with an array list of any data type. :)
Tested, and it did :); thanks again :D


Sign In
Create Account


Back to top









