Last active
August 29, 2015 13:58
-
-
Save ambantis/9986848 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.FileReader; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
public class OpenAFile6 { | |
public String getLine(String fileName, int n) | |
throws IOException, FileNotFoundException, NullPointerException { | |
FileReader reader = null; | |
BufferedReader buf = null; | |
String result = null; | |
try { | |
File file = new File(".", fileName); | |
reader = new FileReader(file); | |
buf = new BufferedReader(reader); | |
for (int i = 1; i < n; i++) | |
buf.readLine(); | |
result = buf.readLine(); | |
} finally { | |
try { | |
if (buf != null) | |
buf.close(); | |
if (reader != null) | |
reader.close(); | |
} catch (Exception e) { | |
// this should never happen | |
} | |
} | |
return result; | |
} | |
} |
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
public class ZMain { | |
public static void main(String[] args) { | |
OpenAFile6 worker = new OpenAFile6(); | |
String fileName = "Main.java"; | |
int n = 5; | |
try { | |
String result = worker.getLine(fileName, n); | |
if (result == null) { | |
System.out.println("Sorry, the line you requested: " + n + | |
", doesn't exist"); | |
} else { | |
System.out.println("Okay, here's the line you requested:\n\t" + result); | |
} | |
} catch (FileNotFoundException e) { | |
System.out.println("Sorry, the file you requested: " + fileName + | |
" , doesn't exist"); | |
} catch (IOException ioe) { | |
System.out.println("Sorry, there was a problem with IO, " + | |
"please try again later"); | |
} catch (NullPointerException npe) { | |
System.out.println("Sorry, but the file name you provided is null"); | |
} catch (Exception e) { | |
System.out.println("Sorry, there was an Internal Server Error, please try again later"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment