Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.BufferedReader;
- import java.util.Random;
- public class RandomLineFromFile {
- /**
- * Program: RandomLineFromFile.java
- * Purpose: Print random line from specified file.
- * Version: Java 7
- * First: First you need to create a text file (e.g. "Phrases.txt")
- * containing a different word or sentence on each line, which this program will use.
- * Usage: Compile this Java source code. If using the JDK, type:
- * javac RandomLineFromFile.java
- * To Run, type
- * java RandomLineFromFile Phrases.txt
- * Then, if you want to make your batch file, type the same:
- *
- * java RandomLineFromFile Phrases.txt
- *
- * (where Phrases.txt is name of your text file - change this if necessary),
- * type into Notepad or other text editor and save as "RandomText.bat" or similar.
- * Run in Command Prompt. Enjoy.
- * Creator: Chris Clarke
- * Created: 26.01.2015
- */
- // declare instance variable
- private static String path;
- // constructor
- public RandomLineFromFile(String filePath) {
- path = filePath;
- }
- public String[] openFile() throws IOException {
- int numberOfLines = countLines();
- if (numberOfLines==0) {
- System.out.println("No such file, or file contained zero lines of text.");
- System.exit(1);
- } // if
- String[] textData = new String[numberOfLines];
- FileReader fr = null;
- BufferedReader textReader = null;
- try {
- fr = new FileReader(path);
- textReader = new BufferedReader(fr);
- for(int i=0; i < numberOfLines; i++) {
- textData[i] = textReader.readLine();
- //System.out.println(textData[i]); // display lines on screen
- } // for
- } catch (IOException e) {
- System.out.println("Couldn't read file!");
- } finally {
- if (textReader!=null) {
- textReader.close();
- } // if
- } // try
- return textData;
- } // openFile()
- public int countLines() throws IOException {
- int numberOfLines = 0;
- FileReader readFile = null;
- BufferedReader bf = null;
- try {
- readFile = new FileReader(path);
- bf = new BufferedReader(readFile);
- String aLine;
- while (( aLine = bf.readLine()) != null) {
- numberOfLines++;
- } // while
- } catch (IOException e) {
- System.out.println("Couldn't read file!");
- } finally {
- if (bf!=null) {
- bf.close();
- } // if
- } // try
- return numberOfLines;
- } // countLines()
- public static void main(String[] args) throws IOException {
- String filename = "MyTextFile.txt";
- if (args.length>0) {
- filename = args[0];
- } // if
- RandomLineFromFile rl = new RandomLineFromFile(filename);
- // create array of lines of text
- String[] lines = rl.openFile();
- // create random object
- Random r = new Random();
- // print a random line
- System.out.println( lines[ r.nextInt( lines.length)]);
- } // main()
- } // class RandomLineFromFile
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement