InputStream
是 Java 中的一個(gè)抽象類,它主要用于從數(shù)據(jù)源(如文件、網(wǎng)絡(luò)連接等)讀取數(shù)據(jù)。在文件讀寫操作中,InputStream
的應(yīng)用主要包括以下幾個(gè)方面:
FileInputStream
類,它是 InputStream
的子類,可以從文件中讀取數(shù)據(jù)。通常與 BufferedReader
或 DataInputStream
結(jié)合使用,以便更高效地讀取文本文件或二進(jìn)制文件。import java.io.*;
public class ReadFileExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream
的子類,如 URLConnection
類的 getInputStream()
方法返回的 InputStream
。import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class NetworkReadExample {
public static void main(String[] args) {
try {
URL url = new URL("https://example.com");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClassLoader
類的 getResourceAsStream()
方法獲取 InputStream
。import java.io.*;
public class ResourceReadExample {
public static void main(String[] args) {
ClassLoader classLoader = ResourceReadExample.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("resources/example.txt");
if (inputStream != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Resource file not found.");
}
}
}
總之,InputStream
在文件讀寫操作中的應(yīng)用非常廣泛,可以用于讀取文件、網(wǎng)絡(luò)數(shù)據(jù)和資源文件。在實(shí)際開發(fā)中,根據(jù)不同的數(shù)據(jù)源選擇合適的 InputStream
子類,并結(jié)合其他工具類(如 BufferedReader
、DataInputStream
等)進(jìn)行高效的數(shù)據(jù)讀取。