Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Writing an contents from an ArrayList to a text file

807603Dec 9 2007 — edited Dec 9 2007
Hi, I am fairly new to Java and I need helop with a program that reads data from text files, places data on an array list and finally writes the contents of the array list to a text file. I have managed to get the read portion of the program to work properly and even displays the contents of the array list using a simple println statement. However, I am having trouble with the writing method of my program. Here is the code:
import java.io.*;
import java.util.*;

public class RowMatcher {

	public static void main (String[] args) {
		readLines();
		writeLines();
	}
	
	public static void readLines() {
		
		ArrayList lines = new ArrayList();
		
		try {
			BufferedReader inTT = new BufferedReader(new FileReader("C:\\TT_PCMAIN33.txt"));
			BufferedReader inSW = new BufferedReader(new FileReader("C:\\SW_PCMAIN33.txt"));
			
			while (true) {
				String TTline = inTT.readLine();
	
				if (TTline == null) {
					break;
				}
				
				String[] TT1 = TTline.split(",");
				lines.add(TT1[0]);
			}
			
			while (true) {
				String SWline = inSW.readLine();
	
				if (SWline == null) {
					break;
				}
				
				String[] SW1 = SWline.split(",");
				
				if (lines.contains(SW1[0])) {
					lines.remove(SW1[0]);
				}
			}
			
			inTT.close();
			inSW.close();
			
			System.out.println(lines);
		}
		
		catch (IOException except) {
			except.printStackTrace();
		}
	}
	
	public static void writeLines() {
		try
		{
			Writer output = null;
		    String text = lines;
		    File file = new File("C:\\Output.txt");
		    output = new BufferedWriter(new FileWriter(file));
		    output.write(text);
		    output.close();
		}
		catch( IOException e )
		{
		   e.printStackTrace();
		}
		
		System.out.println("ArrayList has been written to output text file");
	}
}
At first I get an error saying the variable 'lines' cannot be resolved under the writeLines method. I am not sure how to reference it from the readLines method and I am also not sure if this is the proper way to write the contents of an array list to a text file. Any help would be really appreciated.

Thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 6 2008
Added on Dec 9 2007
5 comments
477 views