Mục lục
Hướng dẫn và ví dụ Java FileInputStream
Xem thêm các chuyên mục:

Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.


FileInputStream là một lớp con của InputStream, nó được sử dụng để đọc các file nhị phân như ảnh, nhạc, video. Dữ liệu nhận được của việc đọc là các bytes thô (raw bytes). Với các file văn bản thông thường bạn nên sử dụng FileReader để thay thế.
public class FileInputStream extends InputStream

FileInputStream constructors
FileInputStream(File file)
FileInputStream(FileDescriptor fdObj)
FileInputStream(String name)
Hầu hết các phương thức của FileInputStream được thừa kế từ InputStream:
public final FileDescriptor getFD() throws IOException
public FileChannel getChannel()
// Methods inherited from InputStream:
public int read() throws IOException
public int read(byte b[]) throws IOException
public int read(byte b[], int off, int len) throws IOException
public byte[] readAllBytes() throws IOException
public byte[] readNBytes(int len) throws IOException
public int readNBytes(byte[] b, int off, int len) throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public synchronized void mark(int readlimit)
public boolean markSupported()
public synchronized void reset() throws IOException
public void close() throws IOException
public long transferTo(OutputStream out) throws IOException
FileChannel getChannel() | Được sử dụng để trả về một đối tượng FileChannel duy nhất liên hợp với FileInputStrem này. |
FileDescriptor getFD() | Được sử dụng để trả về một đối tượng FileDescriptor. |
Ví dụ đầu tiên, chúng ta sử dụng FileInputStream để đọc một file văn bản tiếng Nhật mã hoá UTF-8:
utf8-file-without-bom.txt
JP日本-八洲
Chú ý: UTF-8 sử dụng 1, 2, 3 hoặc 4 bytes để lưu trữ một ký tự. Trong khi đó, FileInputStream đọc từng byte từ file vì vậy bạn sẽ nhận được một kết quả khá lạ lẫm.

FileInputStreamEx1.java
package org.o7planning.fileinputstream.ex;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
public class FileInputStreamEx1 {
public static void main(String[] args) throws MalformedURLException, IOException {
// Windows Path: C:/Data/test/utf8-file-without-bom.txt
String path = "/Volumes/Data/test/utf8-file-without-bom.txt";
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
int code;
while((code = fis.read()) != -1) {
char ch = (char) code;
System.out.println(code + " " + ch);
}
fis.close();
}
}
Output:
74 J
80 P
230 æ
151
165 ¥
230 æ
156
172 ¬
45 -
229 å
133
171 «
230 æ
180 ´
178 ²
Để đọc các file văn bản UTF-8, UTF-16,.. bạn nên sử dụng FileReader hoặc InputStreamReader: