Reputation: 544
I'm a novice in Java. I want to find the number of line in a test file so that I can use it for array size. What my initial thought was to create a loop and update an int variable. like this:
Scanner file = new Scanner(new File("data.text"));
int n = 0;
while(file.hasNextLine()) {
file.nextLine();
n++;
}
int[] array = new int[n];
this doesn't work for me because the scanner file is at the end of the text file. I won't be able to read the text file unless I close the original one and create a new scanner object. Is there a better way to execute this?
Upvotes: 1
Views: 16532
Reputation: 2626
Okay. Here is the simple answer to your question.
You want to use the same Scanner object to read the file again from beginning without closing it.
It is impossible to do so..
Reason: The various kinds of input types it supports.These don't store the results after they have been passed on, so they don't support resetting.
So the elegant solution is to create a new Scanner Object.
Upvotes: 0
Reputation: 7559
Depending on what exactly you need to do, you might want to keep the whole file in memory.
List<String> lines = Files.readAllLines(Paths.get("data.text"));
// Here you can easily obtain the list size
lines.size()
If you don't need the actual lines or not all of them, you can do something like this
long lineCount = Files.lines(Paths.get("data.text")).count();
Since it's a Java 8 Stream, you can filter, parse or do whatever you want with the lines.
Upvotes: 2
Reputation: 4122
You can use BufferedReader
and FileReader
:
FileReader in = new FileReader("data.txt");
BufferedReader br = new BufferedReader(in);// use this only if you have large files, meaning that each line is very long.
int n = 0;
while (br.readLine() != null) {
n++;
}
System.out.println(n);
in.close();
int[] array = new int[n];
Also, you can use an ArrayList
instead of an array, but that would depend on how you want to use the line count.
If your file isn't very big, you can simply do this:
FileReader in = new FileReader("data.txt");
int n = 0;
while ((in.readLine() != null)) {
n++;
}
System.out.println(n);
in.close();
int[] array = new int[n];
Upvotes: 0
Reputation: 2944
If you are using 1.7+, You can directly store to array like this.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// more code
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
Upvotes: 4