Search Particular Column Value from CSV File Using Java

Search particular column value from CSV file using java

Read the file line by line with a BufferedReader wrapped around a FileReader. Stop when you hit a line that startsWith the thing you're looking for. Close the reader and return the line.

Edit:

There's no fancy searching or optimising you can do here, unless the CSV file has some sort of order you haven't mentioned. You just have to read each line until you find the one you want.

How to read a specific column of a row from a csv file in java

I understand that "," is your delimiter so the key is in the algorithm :

    String file = "pathToCsvFile";
BufferedReader reader = null;
String line = "";
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String[] row = line.split(",");
for(int i = 0; i < row.length; i++) {

//HERE I NEED THE DATA OF THE FIRST 2 COLUMNS OF THE ROW
if(i < 2){
System.out.println(i+" -> "+row[i]);
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}

Selecting a particular Column in a CSV-file Dynamically

I need to validate the index to be the index of the column the user enters as an integer ... But it doesn't work.

Arrays.stream(stream).indexOf(columnNS)

There is no method indexOf in the Stream IPA. I'm not sure what did you mean by stream(stream) but this approach is wrong.

In order to obtain the valid index, you need the name of the column. And based on the name, you have to analyze the very first line retrieved from the file. Like in your example with column name "mark", you need to find out whether this name is present in the first row and what its index is.

What I want is to get the column by it's name ... The stream is supposed ...

Streams are intended to be stateful. They were introduced in Java in order to provide to expressive and clear way of structuring the code. And even if you manage to cram stateful conditional logic into a stream, you'll lose this advantage and end up with convoluted code that is less clear performant than plain loop (remainder: iterative solution almost always performs better).

So you want to keep your code clean, you can choose either: to solve this problem using iterative approach or relinquish the requirement to determine the index of the column dynamically inside the stream.

That's how you can address the task of reading the file data dynamically based on the column name with loops:

public static List<String> readFile(Path path, String columnName) {
List<String> result = new ArrayList<>();
try(var reader = Files.newBufferedReader(path)) {
int index = -1;
String line;
while ((line = reader.readLine()) != null) {
String[] arr = line.split("\\p{Punct}");
if (index == -1) {
index = getIndex(arr, columnName);
continue; // skipping the first line
}
result.add(arr[index]);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// validation logic resides here
public static int getIndex(String[] arr, String columnName) {
int index = Arrays.asList(arr).indexOf(columnName);
if (index == -1) {
throw new IllegalArgumentException("Given column name '" + columnName + "' wasn't found");
}
return index;
}
// extracting statistics from the file data
public static DoubleSummaryStatistics getStat(List<String> list) {
return list.stream()
.mapToDouble(Double::parseDouble)
.summaryStatistics();
}

public static void main(String[] args) {
DoubleSummaryStatistics stat = getStat(readFile(Path.of("test.txt"), "mark"));
}

How to read specific columns in CSV file java

Completing your code:

File file = new File("Filename.csv"); 
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
String[] array = line.split(";");
System.out.println(array[0]+" "+array[array.length-1]);
}

You will notice that I changed the comma to a semi-colon as the split separator and added a bit to the println, which will be the last item in your split array.

I hope it helps.

How to access a particular row in a CSV file and update the value in the row?

Simple Steps to do this:

  1. Create a new .csv file

  2. Read your file

  3. While reading your file, write to your new file and do the changes if necessary.

You can also check the similar question here:
what is the best way to edit csv file



Related Topics



Leave a reply



Submit