Henry
Henry

Reputation: 1042

Reading N lines from a file in java?

I am not quite sure how to explain my question but I will try my best. Say for example, I have a file containing 100 numbers, is it possible to read lines 25-50 from this 100 numbers file.

To read N amount from begining, I would do something like this;

ArrayList<Double> array = new ArrayList<Double>();
 Scanner input = new Scanner(new File("numbers.txt"));
 int counter = 0;
 while(input.hasNextLine() && counter < 10)
 {
     array.add(Double.parseDouble(input.nextLine()));
     counter++;
 }

But I am not quite sure how I can go about start reading from a given line e.g. lines 25-50 or 25-75 or 75-100 etc.

Any help is much appreciated and please let me know if my question is not clear.

edit:

Some data in the file:

Upvotes: 1

Views: 2626

Answers (3)

Mikey
Mikey

Reputation: 697

byte[] inputBytes = "line 1\nline 2\nline 3\ntok 1 tok 2".getBytes();
Reader r = new InputStreamReader(new ByteArrayInputStream(inputBytes));

BufferedReader br = new BufferedReader(r);
Scanner s = new Scanner(br);

System.out.println("First line:  " + br.readLine());
System.out.println("Second line: " + br.readLine());
System.out.println("Third line:  " + br.readLine());

System.out.println("Remaining tokens:");
while (s.hasNext())
    System.out.println(s.next());

and add a while loop like Astra suggested

Upvotes: 3

fge
fge

Reputation: 121790

Using Java 8 you have an easy solution. Note that the below code does not make any bounds checking of any kind (this is left as an exercise):

private static final Pattern COMMA = Pattern.compile(",");

public static List<Double> readNumbers(final String file, 
    final int startLine, final int endLine)
    throws IOException
{
    final long skip = (long) (startLine - 1);
    final long limit = (long) (endLine - startLine);
    final Path path = Paths.get(file);

    try (
        final Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8);
    ) {
        return stream.skip(skip).limit(limit)
            .flatMap(COMMA::splitAsStream)
            .map(Double::valueOf)
            .collect(Collectors.toList());
    }
}

It also appears that the problem is unclear; the code above reads all doubles in a given line range. If what you want is to read all doubles from a given start "index" to a given end "index", all you have to do in the code above is change the placement of the .skip().limit() to after the .map().

Upvotes: 3

Astra Bear
Astra Bear

Reputation: 2738

Assuming you have multiple numbers (unknown number of numbers) on each line:

int start = 25;
int n finish = 50;
String delimit = ",";
List<Double> array = new ArrayList<Double>(finish - start);
 Scanner input = new Scanner(new File("numbers.txt"));
 int counter = 1;
 while(input.hasNextLine() && counter <= finish)
 {

        String line = input.nextLine();
        String[] splits = line.split(delimit);
        for (int i=0; i<splits.length; i++){
           if (counter >= start && counter <=finish){
               array.add(Double.parseDouble(splits[i]));
            }
            counter++;
         }
 }

Upvotes: 0

Related Questions