Java中讀取文件流的方法有多種,可以根據不同的需求選擇合適的方法,常見的幾種方法如下:
FileInputStream fis = new FileInputStream("file.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
int c;
while ((c = isr.read()) != -1) {
System.out.print((char) c);
}
isr.close();
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
FileInputStream fis = new FileInputStream("file.bin");
int b;
while ((b = fis.read()) != -1) {
System.out.print(b);
}
fis.close();
以上是幾種常見的讀取文件流的方法,根據具體的需求可以選擇適合的方法。