Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Read CSV line by line JS

I need to read data separated by commas line by line.  The csv files are in /data/name.js.  Each line has 6 columns, ideally I would like to take the data straight from the file and calculate the maximum and minimum of the 4th and 5th columns which are numbers.
Do you want to read this in Java or JavaScript since the file is in JS?
Basically, you would read the file like any other .txt file and then split each line by commas to create a string array.
Here's a quick demo I wrote that should work:
Code
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class test {
    public static void main(String[] args){
        File file = new File("data.csv");
        List<String> lines;
        try {
            lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
            
            for (String line : lines) {
               String[] array = line.split(",");
               int num1 = Integer.parseInt(array[3]);
               int num2 = Integer.parseInt(array[4]);
               if(num1 > num2){
                   //do something
               }
            }
        
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Code taken from https://stackoverflow.com/questions/4510...-file-java


I need to read the file in JS. I think using D3 will work but I have over 50 csv files in the data folder and need to read data from each of them.
I'm not sure I'm getting what you're trying to accomplish. Do you have your 50 comma-separated values compiled into a file with a .js extension or do you want to use JavaScript to read 50 different .csv files?


(Nov 3, 2017 09:23 PM)_wind Wrote:  I'm not sure I'm getting what you're trying to accomplish. Do you have your 50 comma-separated values compiled into a file with a .js extension or do you want to use JavaScript to read 50 different .csv files?

I have 55 different .csv files, all with 6 columns.  Im trying to read those using javascript.
I don't think it's possible with JavaScript for security purposes. Or maybe you can; I don't know. I would, however, use Node.js or PHP.

Why would you ever need to read 50 .csv files in JavaScript though? Couldn't you parse it in Java and output whatever you need?


I agree with Polumon. Unless you're working with a framework for a server, there isn't really a good way to access a local file with JS. If the file can be downloaded via an XHR request, that seems more reasonable.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by GuillyianJul 11, 2022 05:19 AM 5 233 Jul 11, 2022 05:19 AM
Last Post: MavenGradle
[Python] by MomentumAug 24, 2021 03:54 PM 3 204 Aug 24, 2021 03:54 PM
Last Post: Momentum
[Java] by theloharryDec 4, 2020 06:15 AM 7 231 Dec 4, 2020 06:15 AM
Last Post: Rmdy