Click here to Skip to main content
16,021,459 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
help me to know..how can i write arraylist of string on a file ..
Posted
Comments
Sergey Alexandrovich Kryukov 9-Jan-16 3:50am    
What have you tried so far?
What's the problem?
—SA
Member 12200805 9-Jan-16 3:58am    
i can able to get the arraylist on the comment prompt..bt dont know how to write that on a file
Member 12200805 9-Jan-16 4:14am    
import java.util.ArrayList;
public array {
public static void main(String[] args) {
ArrayList <string> elements = new ArrayList<>();
elements.add( one);
elements.add( two);
elements.add( three);
for (int i = 0; i < elements.size(); i++) {
int value = elements.get(i);
System.out.println("Element: " + value);
}
}
}
Member 12200805 9-Jan-16 4:20am    
this is the actual program..i used to get the arraylist..bt want to knw how to get the output on the file...
import java.util.ArrayList;
public class array {
public static void main(String[] args) {

ArrayList <string> elements = new ArrayList<>();
elements.add( one);
elements.add( two);
elements.add( three);
int count = elements.size();
System.out.println( "Count: " + count);
for (int i = 0; i < elements.size(); i++) {
int value = elements.get(i);
System.out.println("Element: " + value);
}
}
}
Maciej Los 9-Jan-16 4:49am    
Use 'Reply' widget if you want to be sure that your interlocutor has been informed.

1 solution

You can use a PrintWriter to do this. Note that the following example will overwrite the file if it already exists. If you don't want this, you can use new File("path/to/file.txt").isFile() to check if a file already exists.
Java
import java.io.PrintWriter;

Java
public static void printArrayListToFile(ArrayList<String> arrayList, String filename) throws IOException {
    PrintWriter writer = new PrintWriter(filename);
    for (String line : arrayList) {
        writer.println(line);
    }
    writer.close();
}

You can call this method in your main method like this:
Java
printArrayListToFile(elements, "output.txt");
 
Share this answer
 
Comments
Member 12200805 9-Jan-16 5:00am    
thank you so much...
ridoy 10-Jan-16 1:37am    
great, a 5.
Thomas Daniels 10-Jan-16 2:28am    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900