1

So I have a large text file full of primes, and I want to be able to ask for a single prime, like the 48th prime for example, and I want Java to read that specific line and return the value. As of now, I have this:

public static void main(String[] args) throws FileNotFoundException {
    ArrayList<Long> primes = new ArrayList<Long>();
    Scanner read = new Scanner(new File("file.txt"));
    Scanner input = new Scanner(System.in);
    System.out.println("Which prime do you want?");
    int in=Integer.valueOf(input.nextLine());
    for(int i=0; i < in; i++){
        if(read.hasNext()){
            long s = Long.valueOf(read.next());
            primes.add(s);
        }
    }
    System.out.println("The "+ in + "th prime is: "+primes.get(in-1));
}

I was wondering if there is an easier way to do this, without having to read the entire file up to the input.

UnsignedByte
  • 849
  • 10
  • 29
  • This question isn't about reading from a particular offset. It involves *finding* that offset. There is no way to do this without looking through the file or building an index that maps line numbers to offsets ahead of time. The filesystem doesn't do that sort of line number indexing automatically. – Chris Martin Dec 04 '16 at 17:30
  • what is data format in the file. Is it just one prime number followed by a newline per line? – TruckDriver Dec 04 '16 at 18:06

0 Answers0