【问题标题】:How do you read contents of a CSV file downloaded into the browser?您如何读取下载到浏览器中的 CSV 文件的内容?
【发布时间】:2019-05-22 10:22:01
【问题描述】:

我需要使用 java 读取托管 CSV 文件的内容。点击托管 CSV 的 URL 会将文件下载到浏览器中。如何访问此文件并读取其内容而无需在本地执行任何操作?

目前我有:

    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();
    }

我希望 products.get("ID")) 从 ID 列中检索数据,而不是得到一个包含符号和乱码的字符串。

有人对我如何实现这一目标有任何想法吗?

提前致谢!

【问题讨论】:

  • 浏览器页面源是什么样的?

标签: java html spring spring-boot


【解决方案1】:

这里要注意两点

  1. BufferedReader 是 Java 中的一个类,它从字符输入流中读取文本,缓冲字符,以便高效读取字符、行和数组。REFER HERE
  2. BufferedReader 中的每一行都是一个字符串输入流,对于 CSV 文件,您需要使用分隔符通常使用“,”来分隔字符串

像这样尝试,希望这是你在这里想要完成的。

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();
    }

谢谢, 快乐编码

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 2012-12-06
    • 2016-11-25
    • 2020-11-19
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多