शुरू करेंमुफ़्त में शुरू करें

CSV फाइलों को सुरक्षित रूप से पढ़ना

अब आप कॉफी सेल्स का एक CSV फाइल पढ़ने के लिए तैयार हैं. डेटा पढ़ने और डेटा टाइप्स वैलिडेट करने के लिए डेटा वैलिडेशन फंक्शंस का उपयोग कीजिए.

ज़रूरी पैकेज जैसे java.time और NumberUtils आपके लिए इम्पोर्ट कर दिए गए हैं.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Java में डेटा क्लीनिंग

पाठ्यक्रम देखें

अभ्यास निर्देश

  • डेट स्ट्रिंग का फ़ॉर्मेट M/d/yy के रूप में पार्स करें.
  • quantity (सेल्स) को Integer के रूप में पढ़ें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

public class CoffeeSalesExample {
    private record CoffeeSales(LocalDate date, String coffeeName, String paymentMethod, Integer quantity, Double amount) {}

    private static LocalDate parseDate(String dateStr) {
    	// Parse the format of the date string
        return ____.____(dateStr, DateTimeFormatter.ofPattern("M/d/yy"));
    }

    private static String validateNumeric(String value) {
        if (NumberUtils.isParsable(value)) return value;
        throw new IllegalArgumentException("Invalid: " + value);
    }
    
    public static double parsePrice(String priceText) {
        if (NumberUtils.isParsable(priceText.replace("$", ""))) {
            return Double.parseDouble(priceText.replace("$", ""));
        }
        throw new IllegalArgumentException("Invalid price: " + priceText);
    }

    public static CoffeeSales parseSalesData(String[] fields) {
        LocalDate publishDate = parseDate(fields[0]);
        String coffeeName = fields[1];
        String paymentMethod = fields[2];
        // Read quantity as an Integer
        Integer quantity = ____.____(validateNumeric(fields[3]));
        Double amount = parsePrice(fields[4]);
        return new CoffeeSales(publishDate, coffeeName, paymentMethod, quantity, amount);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        List sales = new ArrayList<>();
        String filename = "coffee.csv";
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line = reader.readLine();
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(",");
                sales.add(parseSalesData(fields));
            }
        }
        sales.forEach(System.out::println);
    }
}
कोड संपादित करें और चलाएँ