-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileReader.java
More file actions
64 lines (53 loc) · 1.83 KB
/
Copy pathFileReader.java
File metadata and controls
64 lines (53 loc) · 1.83 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.stacktips.exception;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.*;
import java.util.Scanner;
public class FileReader {
private StringBuilder readFile(String filePath) {
try {
Path path = validateFilePath(filePath);
return readFileLineByLine(path);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private Path validateFilePath(String filePath) throws FileNotFoundException {
Path path = Paths.get(filePath);
if (!path.toFile().exists()) {
throw new FileNotFoundException(filePath);
}
return path;
}
public StringBuilder readFileLineByLine(Path path) {
StringBuilder content = null;
try {
BufferedReader br = Files.newBufferedReader(path);
content = new StringBuilder();
String line;
if ((br.readLine()) == null) {
throw new EmptyFileException("This file is empty");
} else {
while ((line = br.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
} catch (NoSuchFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to read file: " + e.getMessage());
}
return content;
}
public static void main(String[] args) {
System.out.println("Enter the path to the file");
Scanner scanner = new Scanner(System.in);
FileReader fileReader = new FileReader();
StringBuilder content = fileReader.readFile(scanner.next());
System.out.println(content);
}
}