Scanner.useDelimiter不适用于基于Web的CSV文件

所以我是Java的初学者,我学习困难,所以请保持简单。我正在研究一种解决方案,它将用户输入英国货币并查找用户输入国家/地区的汇率。不知道我是否在正确的轨道上,但是下面是用户输入要转换的货币金额和国家/地区之后的代码。我需要读取基于Web的CSV文件并将其解析为POJO,但无法使in.useDelimiter正常工作。

public static Double findExchangeRateAndConvert(String currencyType,double amount) throws IOException {


        URL url = new URL("https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/842362/exrates-monthly-1119.csv");
        try (var in = new Scanner(
                new BufferedReader(
                        new InputStreamReader(url.openStream())))) {


            var line = "";
            in.useDelimiter(",");
            while (in.hasnextLine()) {
                line = in.nextLine();

                System.out.println(line);

                if (line.contains(currencyType)) {
                    System.out.println("I found it.");
                    system.exit(0);
                }

                }

            }

        return null;
    }
sunxiangmin 回答:Scanner.useDelimiter不适用于基于Web的CSV文件

使用扫描仪一次读取一行,然后根据regexp拆分该行。逐行处理是一种好方法,因为它很容易了解正在发生的事情。

public class Main {

public static void main(String[] args) throws IOException {
    Double d = Main.findExchangeRateAndConvert("USD",12);

    System.out.println("d=" + d);
}

public static Double findExchangeRateAndConvert(String currencyType,double amount) throws IOException {


    URL url = new URL("https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/842362/exrates-monthly-1119.csv");
    try (var in = new Scanner(
            new BufferedReader(
                    new InputStreamReader(url.openStream())))) {


        var line = "";
        in.useDelimiter(",");
        while (in.hasNextLine()) {
            line = in.nextLine();

            System.out.println(line);

            String[] splitLine = line.split(",");
            if (splitLine[2].equals(currencyType)) {
                System.out.println("I found it.");
                return Double.valueOf(splitLine[3]);
            }
        }
    }

    return null;
}

}

本文链接:https://www.f2er.com/3040844.html

大家都在问