Line 1 Line 2 Line 3 Line 4
------------------ demoReadLinesFromFile Line Count: 4 Lines Read: [Line 1, Line 2, Line 3, Line 4]
private void demoReadLinesFromFile() { // //Note: Many file methods need exception handling as shown here //Assume file "FourLines.txt" is in current (run) directory String path = "FourLines.txt"; List<String> lines = null; //UTF_8 preferred over default //Charset.defaultCharset());#2try { lines =#1Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8); } catch (IOException exeption) { System.out.println("IO exception for -- " + path); System.out.println(exeption.getMessage()); } System.out.println("------------------"); System.out.println("demoReadLinesFromFile"); System.out.println("Line Count: " + lines.size()); System.out.println("Lines Read:"); System.out.println(lines); }
------------------ demoReadTextFromFile Text: Line 1 Line 2 Line 3 Line 4
private void demoReadTextFromFile() { //Here we'll call a helper method String path = "FourLines.txt", text = null; try { text = readFile(path); } catch (FileNotFoundException exeption) { System.out.println("IO exception for -- " + path); System.out.println(exeption.getMessage()); } System.out.println("------------------"); System.out.println("demoReadTextFromFile"); System.out.println("Text:"); System.out.println(text); } public static String readFile(String path) throws FileNotFoundException { //Helper utility method that reads and returns all text from a file path //Note that "\\Z" is a end-of-file character for a text file String content = ""; File file = new File(path); Scanner scanner = new Scanner(file); scanner.useDelimiter("\\Z"); if (scanner.hasNext()) content = scanner.next(); scanner.close(); return content; }
public static void writeFile(String path , String contents) { try { PrintWriter writer = new PrintWriter(path, "UTF-8"); writer.println(contents); writer.close(); } catch(Exception e) { System.out.println("EXCEPTION in writeFile() " + e.toString()); } }
public static void openDefault(String path) { /*Open the parameter file using the operating system's "associated" application -- e.g. HTML likely an internet browser, TXT likely a text editor, etc. NOTE WELL -- This is likely more reliable in Windows than other operating systems */ try { basicOpenDefault(path); } catch (IOException e) { e.printStackTrace(); } } private static void basicOpenDefault(String path) throws IOException { File file = new File(path); if(!file.exists()) throw new FileNotFoundException(); if(!Desktop.isDesktopSupported()) throw new RuntimeException("Java Desktop is not supported in this environment"); Desktop desktop = Desktop.getDesktop(); desktop.open(file); }