-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileReader.java
66 lines (61 loc) · 2.31 KB
/
fileReader.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package fileHandling;
import java.io.*;
import java.util.*;
public class fileReader {
public static void main(String args[]) {
/* Read Data from a file */
try {
FileReader f = new FileReader("D:\\Future\\JavaTutorialbyApnaCollege\\fileHandling\\newfile.txt");
try {
int i;
while ((i = f.read()) != -1) {
System.out.print((char) i);
}
System.out.println();
} finally {
f.close();
System.out.println("File closed");
}
} catch (IOException e) {
System.out.println("An error occurred :" + e.getMessage());
}
/* Read Data from a file --> using FileInputStream */
try {
FileInputStream f = new FileInputStream("D:\\Future\\JavaTutorialbyApnaCollege\\fileHandling\\newfile.txt");
try {
int i;
while ((i = f.read()) != -1) {
System.out.print((char) i);
}
System.out.println();
} finally {
f.close();
System.out.println("File closed");
}
} catch (IOException e) {
System.out.println("An error occurred : " + e.getMessage());
}
/* Read Data from a file --> using BufferedReader */
try (FileReader f = new FileReader("D:\\Future\\JavaTutorialbyApnaCollege\\fileHandling\\newfile.txt");
BufferedReader br = new BufferedReader(f)) {
String line = br.readLine();
if (line != null) {
System.out.println("Data in file : " + line);
} else {
System.out.println("End of file reached.");
}
} catch (IOException e) {
System.out.println("An error occurred : " + e.getMessage());
}
/* Read Data from a file --> using scanner class */
File file = new File("D:\\Future\\JavaTutorialbyApnaCollege\\fileHandling\\newfile.txt");
try {
Scanner sc = new Scanner(file);
String line = sc.nextLine();
System.out.println(line);
sc.close();
} catch (IOException e) {
System.out.println("An error occurred : " + e.getMessage());
}
}
}