read csv file and convert to arraylist javascript code example
Example 1: java read csv file into arraylist
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class CSVReaderInJava {
public static void main(String... args) {
List<Book> books = readBooksFromCSV("books.txt");
for (Book b : books) {
System.out.println(b);
}
}
private static List<Book> readBooksFromCSV(String fileName) {
List<Book> books = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
try (BufferedReader br = Files.newBufferedReader(pathToFile,
StandardCharsets.US_ASCII)) {
String line = br.readLine();
while (line != null) {
String[] attributes = line.split(",");
Book book = createBook(attributes);
books.add(book);
line = br.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return books;
}
private static Book createBook(String[] metadata) {
String name = metadata[0];
int price = Integer.parseInt(metadata[1]);
String author = metadata[2];
return new Book(name, price, author);
}
}
class Book {
private String name;
private int price;
private String author;
public Book(String name, int price, String author) {
this.name = name;
this.price = price;
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + ", author=" + author
+ "]";
}
}
Output
Book [name=Effective Java, price=42, author=Joshua Bloch]
Book [name=Head First Java, price=39, author=Kathy Sierra]
Book [name=Head First Design Pattern, price=44, author=Kathy Sierra]
Book [name=Introduction to Algorithm, price=72, author=Thomas Cormen]
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();
}
}