import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; /** * Reading from a file * @author gtowell * Created Sep 2020 */ public class FileOpen { // the name of the file to be read String fileName; /** Base constructor. * Private so it cannot be used by outsiders */ private FileOpen() { super(); } /** Constructor taking the name of the file to be read * @param fn the name of the file to be read */ public FileOpen(String fn) { this(); fileName=fn; } /** * Use resources to read one line from a file * This is the safer way! */ public void readOneLineTCR() { try (BufferedReader br = new BufferedReader(new FileReader(fileName));) { System.out.println("TCR: " + br.readLine()); } catch (FileNotFoundException e) { System.err.println("Cound not open file " + e); } catch (IOException e) { System.err.println("Problem reading " + e); } } /** * Without Resources. It works, but takes a lot more code */ public void readOneLineTC() { BufferedReader br=null; try { br = new BufferedReader(new FileReader(fileName)); System.out.println("TC: " + br.readLine()); } catch (FileNotFoundException fnf) { System.err.println("Cound not open file " + fnf); } catch (IOException e) { System.err.println("Problem reading " + e); } finally { if (br!=null) { try { br.close(); } catch (IOException ioe) { System.err.println("Problem closing reader " + ioe); } } } } public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in);) { System.out.print("Enter file to be read: "); String name = scanner.nextLine(); new FileOpen(name).readOneLineTC(); new FileOpen(name).readOneLineTCR(); } finally {} } }