Reputation: 79
How can I start reading from the third line of text file in Java? I want to store 12 in 'nodes' variable, 14 in'edges' variable. 12334 in different variable and so on. My input text file consisting of integers goes like this:
12
14
12334 12214 25
32151 32151 85
21514 51454 20
.
.
.
.
.
try
{
for(i=0;i<2;i++)
array[i] = inputFile.nextInt();
nodes=array[0];
edges=array[1];
break;
for(i=2;i<5;i++)
{
array1[i] = inputFile.nextInt();
System.out.println(array1[i]);
}
}
Upvotes: 0
Views: 2042
Reputation: 6747
Note: Having break
is going to terminate the outer loop
Suggestiones how to solve this
1 . Either use BufferReader
or Scanner
class.
2 . Have a counter variable set to zero
3. keep reading line and check if it is equal to 3
yet
4. continue reading line, but when the counter is equal 3
, save each line in either variable or Array
Difference between BufferReader
and Scanner
1. BufferedReader
has significantly larger buffer memory than Scanner. Use BufferedReader
if you want to get long strings from a stream, and use Scanner
if you want to parse specific type of token from a stream.
2. Scanner
can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader
can only read and store String.
3. BufferedReader
is synchronous while Scanner
is not. Use BufferedReader
if you're working with multiple threads.
Upvotes: 0
Reputation: 53829
Using Scanner:
Scanner sc = new Scanner(myFile);
int lineIndex = 0;
while(sc.hasNextLine()) {
String line = sc.nextLine();
if(++lineIndex > 3) {
// do something
}
}
Upvotes: 2