Skip to content

Instantly share code, notes, and snippets.

@mooman219
Created October 22, 2014 06:32
Show Gist options
  • Save mooman219/57430f0673e672f9cff5 to your computer and use it in GitHub Desktop.
Save mooman219/57430f0673e672f9cff5 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Read {
// Scanner used for taking user input.
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
//
// Process the user's input
//
String input = "";
while (true) {
System.out.print("Please enter a filename: ");
input = scanner.nextLine();
if (input.length() == 0) {
System.out.println("Invalid file name.");
} else {
break;
}
}
System.out.println("");
//
// Check if the file exists
//
File file = new File(input);
if (!file.exists()) {
System.out.println("File '" + input + "' does not exist.");
return;
}
//
// Read the file
//
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
// line has text
}
} catch (IOException ex) {
System.out.println("Unable to read file.");
return;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
System.out.println("Unable to close file reader.");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment