Java FileInputStream 使用方法详解:示例与应用场景
以下是几个关于 Java 中 FileInputStream 使用方法的例子:
- 读取文件内容:
File file = new File('example.txt');
try (FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
这个例子展示了如何使用 FileInputStream 来读取一个文件的内容,并将内容打印到控制台上。
- 复制文件:
File sourceFile = new File('source.txt');
File destFile = new File('destination.txt');
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
这个例子展示了如何使用 FileInputStream 和 FileOutputStream 来复制一个文件。它使用一个缓冲区来一次性读取和写入多个字节。
- 读取二进制文件:
File file = new File('image.jpg');
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
// 处理读取的字节数据
}
} catch (IOException e) {
e.printStackTrace();
}
这个例子展示了如何使用 FileInputStream 来读取一个二进制文件,例如图片文件。它使用一个缓冲区来一次性读取和处理多个字节。
这些例子展示了一些常见的 FileInputStream 的使用场景,包括读取文件内容、复制文件和读取二进制文件。根据具体需求,你可以根据这些例子进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/fOl7 著作权归作者所有。请勿转载和采集!