Overview


Here we'll demo some of Java's utilities for reading from text files.


Text File
Here is the file we'll play with for these examples (with highly imaginative file contents)
Line 1
Line 2
Line 3
Line 4
Read Lines
  • 1. Read all the lines in the file using the "Files" utility method readAllLines
  • 2. The try-catch is typical for many file operations. The compiler will tell you when you need to catch an exception, and you can use a similar try-catch statement.

Here is the output:
------------------
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());

	
#2
try { lines =
#1
Files.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); }
Read Text
Here we read the entire file contents as a String. The helper method readFile is where the work happens. We open a scanner on the path and read up to the end-of-file marker.

Here is the output:
------------------
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;
}
Write Text
Here we write a string to a file.
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()); }
}

Opening File With Associated Application


Below demo's how to open a file using the operating system's associated application. For example:


Notes:

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);
}