how to write arraylist to csv file in java code example
Example 1: java create csv file from list
String input = "[\"user1\",\"track1\",\"player1\", \"user1\",\"track2\",\"player2\", \"user1\",\"track3\",\"player3\"]";
input = input.substring(1, input.length() - 1);
String[] split = input.split(" ");
FileWriter writer = new FileWriter("/Users/user/tmp/csv/sto1.csv");
for(String s : split) {
String[] split2 = s.split(",");
writer.write(Arrays.asList(split2).stream().collect(Collectors.joining(",")));
writer.write("\n");
}
writer.close();
Example 2: convert arraylist to csv file java
import java.util.ArrayList;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
class test
{
public static void main(String arg[])throws IOException
{
ArrayList<String> list1 = new ArrayList<>();
list1.add("2212");
list1.add("gmail.com");
ArrayList<String> list2 = new ArrayList<>();
list2.add("192.168.0.175");
list2.add("403");
list2.add("192.168.0.26");
list2.add("1809");
File file = new File("test.csv");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Domain,Total");
bw.newLine();
for(int i=0;i<list1.size();i++)
{
bw.write(list1.get(i+1)+","+list1.get(i++));
bw.newLine();
}
bw.write("\nApplication,Total");
bw.newLine();
for(int i=0;i<list2.size();i++)
{
bw.write(list2.get(i++)+","+list2.get(i));
bw.newLine();
}
bw.close();
fw.close();
}
}