Right, yes that makes more sense, here is the update method:
public List<String> fileInArray(){//save file text into array
Path path = Paths.get(fileName);
if(!(Files.isReadable(path))){
System.out.println("The file is empty. You need to save something in it first.");//to be printed in the textArea
return null;
}
try{
return Files.readAllLines(path, ENCODING);
}
catch(IOException ioexception){
System.err.println("General Error with IO");
ioexception.printStackTrace();
System.exit(1);
}
return null;
}
If there is no file in the folder, which would be when you run the application the first time, you get this in the console (and the application doesn't run at all): I believe that's correct
G:\JAVA\GUI\2015\createFrames\files\withSearch>java SentenceRecorderTest
The file is empty. You need to save something in it first.
Array contains:
Exception in thread "main" java.lang.NullPointerException
at SentenceRecorder.printSentenceArray(SentenceRecorder.java:187)
at SentenceRecorder.<init>(SentenceRecorder.java:72)
at SentenceRecorderTest.main(SentenceRecorderTest.java:5)
G:\JAVA\GUI\2015\createFrames\files\withSearch>
The reason why you get "array contains:" is because the function that prints the array
public void printSentenceArray(){
System.out.println("Array contains: ");
for(int count = 0; count < allSentences.size(); count++){
//System.out.printf("%s", allSentences.get(count));
System.out.println(allSentences.get(count));
}
}
runs anyway as it is called from inside the constructor:
public SentenceRecorder(){
...
fileName = "sample.txt";
file = new File(workingDir, fileName);
allSentences = fileInArray();//copying content of file in arrayList
printSentenceArray();
setLayout(gbLayout);//set layout of jframe
...
}//end of constructor
You just need to load allSentences once, when you initialise the program.
yep that's done in the constructor above allSentences = fileInArray();
searching does not belong anywhere in that code.
I have a separate function for that, still haven't coded much as yet, but the idea is that, for now, i call it with a hardcoded string in it and use that as search term. Is it safe to call that function from the constructor or should it be called from inside public List<String> fileInArray(){}
?
public String searchWord(String keyword){// search for keyword and return the whole string/s
System.out.printf("Keyword is %s", keyword);
return keyword;
}