-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBookReader.java
More file actions
58 lines (48 loc) · 1.51 KB
/
BookReader.java
File metadata and controls
58 lines (48 loc) · 1.51 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
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// Here necessarily inherited from JFrame
public class BookReader {
// Fields should be private
private FileDialog fileDialog;
private BookReaderCallback callback;
// Nested callback interface
public interface BookReaderCallback {
// Method will be invoked when a text file is read successfully by the end of
void onReadComplete(String text);
}
// In the constructor pass the parent frame
// Instantiate it is not necessary in this class
public BookReader(Frame parent) {
fileDialog = new FileDialog(parent, "Select book", FileDialog.LOAD);
}
public void readBook() {
// Show () deprecated so call "setVisible"
fileDialog.setVisible(true);
if (fileDialog.getDirectory() == null || fileDialog.getFile() == null) {
return;
}
Scanner in = null;
String text = "";
try {
in = new Scanner(new File(fileDialog.getDirectory(),
fileDialog.getFile()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (in.hasNext()) {
text += in.nextLine() + "\n";
}
in.close();
// Read the file, and now through the object class obratnogo call
// notifitsiruem calling class about the text read and pass it the result
if (callback != null) {
callback.onReadComplete(text);
}
}
public void setCallback(BookReaderCallback callback) {
this.callback = callback;
}
}