Ví dụ đọc dữ liệu từ file text có cấu trúc.

E viết chương trình đổi tiền, muốn class program của mình nhận vào một bảng tỷ giá là file .txt. nhưng ko biết làm sao duyệt qua từng phần tử trong bảng tỷ giá. Em định dùng List để chứa bảng tỷ giá này. Trong lớp tỷ giá có ngoại tệ (String), tỷ giá mua(double), tỷ giá bán(double). Và bảng tỷ giá là một danh sách các tỷ giá. Mong các anh chị giúp dùm.

Đầu tiên bạn lưu tỷ giá vào một file rates.txt có nội dung như sau:

USD,17000,16800
EURO,27000,26500

Chúng ta sử dụng đối tượng Rate để lưu thông tin về mỗi tỷ giá:

/**
* Rate class to store rate's informations
*
* @author cuonglm
*
*/
class Rate {
private String name;

private int buy;

private int sell;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getBuy() {
return buy;
}

public void setBuy(int buy) {
this.buy = buy;
}

public int getSell() {
return sell;
}

public void setSell(int sell) {
this.sell = sell;
}

@Override
public boolean equals(Object obj) {
if (obj == null && !(obj instanceof Rate))
return false;
Rate rate = (Rate) obj;
if (name != null && name.equals(rate.getName()) && buy == rate.getBuy()
&& sell == rate.getSell())
return true;
return false;
}

@Override
public int hashCode() {
return super.hashCode();
}

@Override
public String toString() {
return "Rate " + name + "(" + buy + "," + sell + ");";
}

}

Sau đó chúng ta viết lớp Demo để đọc file rates.txt với các yêu cầu sau:
+ Danh sách các đối tượng Rate được lưu vào Set để không có tỷ giá nào trùng nhau.
+ Bất cứ lỗi IO nào sẽ ngừng chương trình ngay lập tức.
+ Nếu một dòng có định dạng không đúng thì bỏ qua và đọc dòng tiếp theo

public class Demo {
private static final String RATE_FILE = "rates.txt";

@SuppressWarnings("unchecked")
public static void main(String args[]) {
try {
// Array list to store all rates
Set rates = new HashSet();
String tempStr = null;
BufferedReader br = null;

// Try to read file with BufferedReader
br = new BufferedReader(new FileReader(RATE_FILE));

Rate rate = null;
StringTokenizer st = null;
// Read each line and create Rate object
while ((tempStr = br.readLine()) != null) {
st = new StringTokenizer(tempStr, ",");
if (st.countTokens() == 3) {
try {
rate = new Rate();
rate.setName(st.nextToken());
rate.setBuy(Integer.valueOf(st.nextToken()));
rate.setSell(Integer.valueOf(st.nextToken()));
rates.add(rate);
} catch (Exception e) {
continue;
}

}
}

for (Rate rt : rates) {
System.out.println(rt);
}
} catch (FileNotFoundException e) {
System.out.println("Rate file not found!");
} catch (IOException e) {
System.out.println("Error while read rate data: " + e.getMessage());
}
}
}

Tớ chưa test tất cả các case nên có thể có bug nhưng về cơ bản là thế.

Leave a Reply