-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadDataFromFile.java
59 lines (48 loc) · 1.36 KB
/
ReadDataFromFile.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
package com.javamultiplex.filehandling;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReadDataFromFile {
public static void main(String[] args) throws IOException {
Scanner input = null;
BufferedReader br = null;
try {
input = new Scanner(System.in);
System.out.println("Enter file name with extension : ");
String fileName = input.nextLine();
if (isValidFileName(fileName)) {
// Here i am assuming file is present in current directory.
FileReader reader = new FileReader(fileName);
br = new BufferedReader(reader);
String line = br.readLine();
System.out.println("Following data is present in file "
+ fileName+" : ");
while (line != null) {
System.out.println(line);
line = br.readLine();
}
} else {
System.out.println("File name is invalid.");
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} finally {
if (input != null) {
input.close();
}
if (br != null) {
br.close();
}
}
}
private static boolean isValidFileName(String fileName) {
String pattern = "^.+\\..+$";
boolean result = false;
if (fileName.matches(pattern)) {
result = true;
}
return result;
}
}