Hi all,

i'm trying to get a specific line in a text from a text file.
In fact i want to read just the eight first line from my text file.
It's only return the four first line. why?

here is my code but, there is Format problem.

import java.io.*;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class ReadLine

public static void main(String[] args) 
//String chaine = null; 
// read the file 
try { 
InputStream ips = new FileInputStream("File.txt"); 
InputStreamReader ipsr = new InputStreamReader(ips); 
BufferedReader br = new BufferedReader(ipsr); 
String ligne; 
int numLigne =0;
int nombreDeLignes =8; 
int[] var = new int[nombreDeLignes ];

while ((ligne = br.readLine()) != null) 
//chaine += ligne + "\n"; 
int ind = ligne.indexOf(" ");
var[numLigne -1] = Integer.parseInt(ligne.substring(0, ind));

for (int i = 0; i < var.length; i++) 
System.out.println("var[" + i + "] = " + var[i]); 

catch (Exception e) 

Recommended Answers

ReadLine program can read txt files with max. 8 lines without errors. Your File.txt contains only four lines. Check it.

Jump to Post

All 4 Replies

ReadLine program can read txt files with max. 8 lines without errors. Your File.txt contains only four lines. Check it.


my text file has more than 100 lines.

Use ArrayList class. It's size (length) grows automatically when you add an element.


You say that you want to read the eight first line from my text file but
your while loop is set to continue as long as the lines to read is not null. Your int[]var on the other hand has the length of 8 which means that you will get a ArrayIndexOutOfBoundsException when you come to line number nine in your text file. Maybe you should set a condition that stops either when the array is filled or the lines to read are null.

You are aware of ( I hope) that your int[]var only can accept strings that can be converted to numbers by Integer.parseInt(ligne.substring(0, ind), like 1, 2, 3. So if you have any other chars like a, b, c in your text you will get a NumberFormat error. What you catch is the first "word" in the line because
int ind = ligne.indexOf(" ") counts the chars until the first empty space " " appears.

Both your while loop and for loop works fine according to the conditions you have set up, if you test them one by one.

Think about this...
Does the while loop work as you want it to do?
Is an int array the best to use?
Has your array so many places it needs in this program?
Do you get the output you want in ligne.indexOf(" ")?
Has the text only numbers?

Good luck =)

Be a part of the DaniWeb community

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