2

Can someone tell me how can i read csv file by each row and column wise in java without using external jars.

I have tried the below code but here i am able to read only one column at a time.

public class ParseCSVs{
public static void main(String[] args) throws Exception {
    File file = new File("./input//SIMNumbers.csv");
    List<String> lines = Files.readAllLines(file.toPath(),StandardCharsets.UTF_8);
    for (String line : lines) {
        String[] array = line.split(",");
        System.out.println(array[2]);
    }
}}

Thanks in advance.

2
  • 1
    you aren't reading line by line but everything at once and iterate over the lines. this will break with large files due to massive memory consumption. Commented Dec 8, 2014 at 11:57
  • @M.Deinum can you tell me how can i split each row and how can i print particular row data. Commented Dec 8, 2014 at 12:13

2 Answers 2

3

Assuming you are using Java 8 you can use streams. For this there is a lines method on the Files class. Next you need to map from a String to a String[] which you can then process.

public class ParseCSVs{

    public static void main(String[] args) throws Exception {
        File file = new File("./input//SIMNumbers.csv");
        Files.lines(file.toPath(),StandardCharsets.UTF_8)
             .substream(1)
             .map(line -> Arrays.toList(line.split(",")))
             .forEach(System.out::println);
    }
}

The code above reads the file line by line, maps the line to a String[] which in turn is turned into a List. This list is finally printed to the console.

Sign up to request clarification or add additional context in comments.

3 Comments

can you please be more specific on how can i print a particular row data. let us say in row1: 1,2,3 columns and row2: 4,5,6. How can i print row2 data.Is possible can you provide me some code snippet
Hello Deinum i am expecting this. if i have 3 rows with 3 columns suppose if i enter row number 2 i want to get the entire row2 data and print on console
Then don't use the approach here. Use a LineNumberReader and read until the lineNumber matches the line you actually want. Use it to read line by line.
0

You can use a Scanner class: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Here is example from some page from google search: http://www.journaldev.com/2335/how-to-read-csv-file-using-java-scanner-class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.