I think I made a good FileIO object because I can simply copy-paste whenever I need, however I wonder How I can improve my code.
This code takes file path of the target file and turns every line to Strings. And combine all of the Strings into String array so that we can use the data of the file.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileIO {
private BufferedReader br;
private FileInputStream fIn;
private String fileName;
private int length;
private String[] data;
public FileIO(String fileName) throws IOException {
this.fileName = fileName;
createFile();
setLength();
setData();
fIn.close();
br.close();
}
private void createFile() {
try {
fIn = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(fIn));}
catch (FileNotFoundException e) {
System.out.println("ERROR! " + fileName + " named file does not found!");
System.exit(-1);
}}
private void setLength() throws IOException {
length = 0;
br.readLine(); // if first line of the file is not title, delete this.
while((br.readLine()) != null) {
length++;
}}
private void setData() throws IOException {
data = new String[length];
fIn.getChannel().position(0);
br = new BufferedReader(new InputStreamReader(fIn));
br.readLine(); // if first line of the file is not title, delete this.
for (int i = 0; i < length; i++) {
data[i] = br.readLine();}
}
public int getNumberOfLines() {
return length;
}
public String[] getAllData() {
return data;
}
public String getDataLine(int lineNumber) throws Exception {
if (length < lineNumber) {
throw new Exception("Line number is greater than all of the lines! Please enter a number between 0 and " + length);}
return data[lineNumber-1];}
}