Created
October 22, 2014 06:32
-
-
Save mooman219/57430f0673e672f9cff5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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