Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ArrayList and casting

Status
Not open for further replies.

jisoo22

Programmer
Apr 30, 2001
277
0
0
US
Hello,

I have a problem with an ArrayList. My program is supposed to take all the elements of that array and write them to a text file. Unfortunately it doesn't. I think it may be a casting issue as ArrayList's get method only returns objects. But after casting those objects into strings, still no go. Here's a little snippet of my code below. Does anyone have any ideas?

Thanks,
Jisoo22

Code:
	public static void saveModel(String outFileName, ArrayList stringList)
	{

		ArrayList list = stringList;

		try
		{
			FileWriter wr = new FileWriter(outFileName);
			BufferedWriter outFile = new BufferedWriter (wr);

			for(int i = 0; i < list.size(); i++)
			{
				outFile.write((String)list.get(i));  // <---- It looks to be this is the culprit.  Somehow
													 // <---- the elements of stringArray do not get written
													 // <---- to the new text file despite being cast as
													 // <---- strings for the stringBuffer's write method.
													 // <---- How does this work???

				outFile.newLine();
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}//saveModel
 
I must apologize for the multiple entries, I think my computer at work crashed and somehow entered in my query several times.

Thanks,
Jisoo22
 
You never close the writer in the code you gave. Since the output is buffered, this means that it won't be written until it is flushed, which happens when the writer is closed.
 
meandanale is correct.

if you wish to keep the file open however, you can call
Code:
outFile.flush()
to flush the contents of the buffer to the disk. Its recommended you do this ever so often anyway if the loop is a long one, since if your computer dies all the data that you have &quot;written&quot; to disk, but not actually flushed will be lost.
-------------------------------------------
There are no onions, only magic
-------------------------------------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top