简体   繁体   中英

How do you read contents of a CSV file downloaded into the browser?

I need to read the contents of a hosted CSV file using java. Hitting this URL where the CSV is hosted downloads the file into the browser. How do I access this file and read its contents without having to do anything locally?

Currently I have:

    try {

        URL url = new URL("URL here");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        CsvReader products = new CsvReader(in);

        products.readHeaders();

        while (products.readRecord()) {
            products.get("ID"));
            }
        }
        products.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

I expect the products.get("ID")) to retrieve data from the ID column instead I get a string containing symbols and gibberish.

Does anyone have any ideas on how I may achieve this?

Thanks in advance!

Two main points to be noted here

  1. BufferedReader is a class in Java that reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, lines, and arrays. REFER HERE
  2. each row in BufferedReader is a String Input stream you need to separate the string with separator usually a ',' for CSV files

Try like this hope this is what you are trying to accomplish here.

try {

        URL url = new URL("URL here");
       URLConnection urlConn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                    ((URLConnection) urlConn).getInputStream()));

         String row;
         while ((row = in.readLine()) != null) {
            String[] values = row.split(","); // separator
            System.out.println("Product ID= " +values[0]); // change 0 to the column index of the file 

            }

       in.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Thanks, Happy Coding <3 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM