Member Avatar for Lioshenka

Hi there!!!
I am back with more problems, now in Java :)

What I am trying to do is to make an application to read and output a random line from a text file, but everything I know how to do is to output the whole lot. How can I access and output a RANDOM line from a file???

My current class is as follows:

package Talking;

import java.io.*;

public class Talking{
    public static void main(String[] args) throws IOException{
      File f;
    f=new File("Talking.txt");

      if(!f.exists()&& f.length()<0)
      System.out.println("The specified file does not exist");

      else{
         FileInputStream finp=new FileInputStream(f);
      byte b;
    do{
      b=(byte)finp.read();
      System.out.print((char)b);
    }
      while(b!=-1);
        finp.close();
        }
    }
  }

The file, if anyone interested is something like

String 1
Line 2
Blablabla
The sound of the sea

Use a BufferedReader with the readLine() method. You can either skip lines as you read them, or place each line into an ArrayList, and process them as needed.

Member Avatar for Lioshenka

How do I do it??? I've just tried to do something like that, and this is what I came up with

package Talking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;



public class Talking{
	
	    public static void main(String[] args) throws FileNotFoundException{
		int start;
		int end;
		start=0;
		end=10;
		int num = (int)(start + (Math.random() * (end-start)));
		System.out.println(num);
		
		
		
	    public  void readLineFromFile() {
	    	
	           try {
	           BufferedReader br = new BufferedReader(new FileReader("talking.txt"));
	          String thisLine = br.readLine(); 
	           System.out.println(thisLine);
	           } // end try
	          
	         catch (IOException e) {
	           System.err.println("Error: " + e);
	         }
	      } 
	      
	 }

Now, how can I pass the num integer as an arguement for the readLine method? Am I thinking in a right direction?

I print out the random value just to be sure it works. I will comment it out later.

readLine() just sequentially reads lines from the file. If you only care about certain lines, maintain a counter as the lines are read and print/store/whatever lines you need based upon that counter.

int lineNumber=0;
String line=null;
while ( (line = br.readLine()) != null){
  lineNumber++;
  if ( <some expression on lineNumber> ){
    // do something
  }
}

If you want to randomly present lines from the file, I would read all of the lines into an ArrayList first and then get() them with a random int of the range 0 to size()-1.

Member Avatar for Lioshenka

Thanks a lot, I got it to work now!

Look into the RandomAccessFile class. The only downside being the file is a treated as a sequence of bytes rather than the conventional line oriented view which many are used to. This class is especially for example useful when you want to come up with your custom file format which would have a fixed header size.

Member Avatar for Lioshenka

Simple question now :) Now I have made another program, which reads 85 random characters from file one by one and outputs them onto the screen. The thing is, that for some reason the output is produced on a number of lines, instead of just one. I dont know what causes it. The number of lines can vary, e.g. with 85 characters output it could be 2 lines, up to about 7. Any suggestions, please?

If there isnt a very simple solution, just say so, this is not crucial - my tutor only asks for random characters output :)

I am not quite sure that I understand what you are trying to say here but if you are worried about the number of characters displayed per line on your console window, it depends on the properties of the console window (OS specific) and has got nothing to do with your program. For e.g. in Windows you can set the properties of the console window like Screen buffer and window size to increase / display the number of characters displayed.

If still in doubt, post the code along with the varying output you are talking about.

Member Avatar for Lioshenka

I think, I got it while I was lying in the bed yesterday. Does /n (line break) counts as a character??? If yes, is there an easy way to avoid reading it?

PS the lines in console window break wherever they want, so for example the sample output would be like
asd as iasd. ad
as
hfb jd
o8 fg.dnc;

Yes, even whitespace counts as a character. To detect a whitespace, use the function Character.isWhitespace(char ch) .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.