-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTxtFileLineRead.java
More file actions
90 lines (81 loc) · 2.46 KB
/
TxtFileLineRead.java
File metadata and controls
90 lines (81 loc) · 2.46 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
*
* @author Yuan Yifan
* Function: Read large text file line by line.
* Usage:
* Firstly, new a object TxtFileLineRead and initial it by your filename:
* TxtFileLineRead FRL = new TxtFileLineRead(FileName);
* Secondly, the function in this object fReadln to return a line.
* For example:
* String Exper = FRL.fReadln();
* If the text file has N lines you have to execute this function for N times to read it all
* Last but not least:
* You have to free file before terminating your program like this:
* FRL.FreeFile();
* Have fun!
*
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TxtFileLineRead {
//public static void main(){
// You can write Usage in main or a new function.
// Such as:
// System.out.println("Firstly, new a object TxtFileLineRead and initial it by your filename:");
// And so on
//}
private FileReader fp = null;
private BufferedReader br = null;
private int Flag_Loaded = 0;
public TxtFileLineRead(String FileName){
LoadFile(FileName);
}
public TxtFileLineRead(){
//Do nothing
}
public int LoadFile(String FileName){
//Using for debug
System.out.println("Try to load " + FileName);
try{
if (Flag_Loaded==1){
FreeFile();
}
fp = new FileReader(FileName);
br = new BufferedReader(fp);
Flag_Loaded = 1;
return(0);
}catch (FileNotFoundException e){
System.out.println("Error while loading file.");
return(-1);
}
}
public String fReadln(){
try {
String Str = br.readLine();
return(Str);
} catch (IOException ex) {
System.out.println("Error while get the line");
Logger.getLogger(TxtFileLineRead.class.getName()).log(Level.SEVERE, null, ex);
return(null);
}
}
public void FreeFile(){
try {
if (Flag_Loaded != 0){
br.close();
fp.close();
Flag_Loaded = 0;
}
} catch (IOException ex) {
Logger.getLogger(TxtFileLineRead.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void finalize() throws Throwable{
FreeFile();
}
}