|
| 1 | +package com.gnguyen92.springdemoannotations; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.File; |
| 5 | +import java.io.FileNotFoundException; |
| 6 | +import java.io.FileReader; |
| 7 | +import java.io.IOException; |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +import org.springframework.stereotype.Component; |
| 12 | + |
| 13 | +@Component |
| 14 | +public class FileRandomSkill implements SkillLevel { |
| 15 | + |
| 16 | + private String filepath = "C:/Users/gnguy/Desktop/Java/spring-demo-annotations/src/skillLevel.properties"; |
| 17 | + private List<String> skillLevels; |
| 18 | + |
| 19 | + // create default constructor to read file and store values into array |
| 20 | + public FileRandomSkill() throws IOException { |
| 21 | + File file = new File(filepath); |
| 22 | + |
| 23 | + System.out.println(">> Reading from file " + filepath); |
| 24 | + System.out.println(">> File exists: " + file.exists()); |
| 25 | + |
| 26 | + // initialize the array |
| 27 | + skillLevels = new ArrayList<String>(); |
| 28 | + |
| 29 | + // read from the file |
| 30 | + try { |
| 31 | + BufferedReader br = new BufferedReader( |
| 32 | + new FileReader(file)); |
| 33 | + |
| 34 | + // Add each line into skillLevels[] |
| 35 | + String temp; |
| 36 | + while((temp = br.readLine()) != null) { |
| 37 | + skillLevels.add(temp); |
| 38 | + } |
| 39 | + |
| 40 | + br.close(); |
| 41 | + |
| 42 | + } catch (FileNotFoundException e) { |
| 43 | + e.printStackTrace(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // ArrayList length method: arrayList.size() |
| 48 | + // ArrayList element at index: arrayList.get(i) |
| 49 | + public String getSkillLevel() { |
| 50 | + int randomIndex = (int)Math.floor(Math.random() * skillLevels.size()); |
| 51 | + return skillLevels.get(randomIndex); |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments