forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileInputStreamExample.java
More file actions
44 lines (40 loc) · 1.22 KB
/
FileInputStreamExample.java
File metadata and controls
44 lines (40 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.examplehub.basics.io;
import java.io.*;
public class FileInputStreamExample {
public static void readFile(String filename) throws IOException {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filename);
int read;
while ((read = inputStream.read()) != -1) {
System.out.print((char) read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
assert inputStream != null;
inputStream.close();
}
}
public static void readFileWithTryRecourse(String filename) throws FileNotFoundException {
try (InputStream inputStream = new FileInputStream(filename)) {
int read;
while ((read = inputStream.read()) != -1) {
System.out.print((char) read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readFileWithBuffer(String filename) throws IOException {
try (InputStream inputStream = new FileInputStream(filename)) {
byte[] buffer = new byte[1024];
int readBytes;
while ((readBytes = inputStream.read(buffer)) != -1) {
for (int i = 0; i < readBytes; i++) {
System.out.print((char) buffer[i]);
}
}
}
}
}