Đọc dữ liệu từ tập tin văn bản
a. Sử dụng lớp FileReader
Thông thường để đọc/ghi file người ta thường dùng luồng byte, nhưng đối với luồng ký tự chúng ta cũng có thể thực hiện được. Ưu điểm của việc dùng luồng ký tự là chúng thao tác trực tiếp trên các ký tự Unicode. Vì vậy luồng ký tự là chọn lựa tốt nhất khi cần lưu những văn bản Unicode.
Hai lớp luồng thường dùng cho việc đọc/ghi dữ liệu ký tự xuống file là FileReader và FileWriter.
Ví dụ: Đọc những dòng văn bản nhập từ bàn phím và ghi chúng xuống file tên là “test.txt”. Việc đọc và ghi kết thúc khi người dùng nhập vào chuỗi “stop”.
import java.io.*;
class iodemo {
public static void main(String args[]) throws IOException {
String str;
FileWriter fw;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
fw = new FileWriter("D:\\test.txt");
} catch (IOException exc) {
System.out.println("Khong the mo file.");
return;
}
System.out.println("Nhap ('stop' de ket thuc chuong trinh).");
do {
System.out.print(": ");
str = br.readLine();
if (str.compareTo("stop") == 0) {
break;
}
str = str + "\r\n";
fw.write(str);
} while (str.compareTo("stop") != 0);
fw.close();
}
}
Ví dụ
import java.io.*;
class DtoS {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
b. Sử dụng lớp Scanner
Với Java 1.5 trở đi, có thể sử dụng lớp Scanner trong gói java.util để đọc dữ liệu từ tập tin văn bản:
Scanner f = new Scanner(new File("ten.txt"));
Ví dụ:
void ReadFile(String filename)
{
try
{
FileInputStream f=new FileInputStream(filename);
Scanner input=new Scanner(f,”UTF-8″);
int i=1;
while(input.hasNextLine())
{
String line=input.nextLine();
System.out.println((i++)+”. “+line);
}
f.close();
input.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Nội dung đầy đủ:
import java.io.*;
import java.util.Scanner;
class ReadFileDemo{
void ReadFile(String filename) {
try {
FileInputStream f = new FileInputStream(filename);
Scanner input = new Scanner(f,"UTF-8");
int i = 1;
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println((i++) +". "+line);
}
f.close();
input.close();
} catch (IOException e) {
}
}
}
public class ScannerReadFileDemo {
public static void main(String[] args) {
ReadFileDemo rfObj = new ReadFileDemo();
rfObj.ReadFile("d:\\test.txt");
}
}
Trương Đình Huy
» Tin mới nhất:
» Các tin khác: