You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Example code to read a text file named ’filename.txt’ line by line, and adding the
contents to an array list:
publicstaticArrayList<String> readFile(){
ArrayList<String> list = newArrayList<String>();
try{
//the file to be opened for readingFileInputStreamfis=newFileInputStream("filename.txt");
Scannersc=newScanner(fis); //file to be scanned//returns true if there is another line to readwhile(sc.hasNextLine()){
Stringline = sc.nextLine();
list.add(line);
}
sc.close(); //closes the scanner
}
catch(IOExceptione){
e.printStackTrace();
}
returnlist;
}
Try-catch statement in Java allows us to run a block of code and test it for the
potential errors at the same time. This code is written in try block. If the error
happens, code in the catch block will be executed.
We can optionally have a finally
statement after catch, and it will be executed after try-catch, regardless of what
happens.
If we do not use catch block, we have to add throws keyword to our method signature.