Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Program Description:
- Program takes a line of text from a text file (excerpt) and outputs it on the console. The program also prints the
- entire text file from which the excerpt was taken. The name of the text file to be used is to be inputted as a command line argument.
- */
- import java.io.*;
- import java.util.Random;
- import java.io.FileReader;
- import java.io.File;
- public class Main
- {
- BufferedReader reader = null;
- File filename = null;
- String line;
- LineNumberReader lnr = null;
- FileReader fr = null;
- int numOfLines=0;
- public Main (String nameOfTextFile)
- {
- try
- {
- filename = new File(nameOfTextFile);
- reader = new BufferedReader(new FileReader(filename));
- fr = new FileReader(filename);
- lnr = new LineNumberReader(fr);
- }
- catch(FileNotFoundException e)
- {
- System.out.println("Error: text file does not exist");
- }
- catch(Exception e)
- {
- System.out.println("General Errors");
- }
- }
- public void printAllLines ()
- {
- try
- {
- line = reader.readLine();
- while (line != null)
- {
- System.out.println(line);
- line = reader.readLine();
- }
- reader.close ();
- }
- catch(Exception e)
- {
- System.out.println("Error: file manipulation error");
- }
- }
- public void getExcerpt ()
- {
- try
- {
- int startingLineNum=0;
- int endingLineNum=0;
- int lineCount=0;
- Random rand = new Random();
- line = reader.readLine();
- while (line != null)
- {
- System.out.println(line);
- line = reader.readLine();
- numOfLines ++;
- }
- while (line != null)
- {
- System.out.println(line);
- line = reader.readLine();
- numOfLines ++;
- }
- startingLineNum = rand.nextInt(numOfLines);
- endingLineNum = rand.nextInt(numOfLines);
- }
- catch(Exception e)
- {
- System.out.println("Error: file manipulation error");
- }
- finally
- {
- }
- }
- public static void main(String[] args) throws Exception
- {
- try
- {
- Main excerptDemo = new Main (args[0]);
- System.out.println ("\nText File Excerpt:\n");
- excerptDemo.getExcerpt ();
- System.out.println ("\nExcerpt taken from: \"" +excerptDemo.filename.getName() + "\"\n");
- excerptDemo.printAllLines ();
- //the two bolded methods are the methods that can't seem to work together
- }
- catch (ArrayIndexOutOfBoundsException e)
- {
- System.out.println("Error: Name of text file was not specified in command line argument");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment