1

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?

Ajmal
  • 484
  • 1
  • 7
  • 14
  • 1
    Use a [`List`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html) instead of an array. Or start with a fixed array size and "resize" the array, when needed (create an array of double the size, copy the old content to the new array). Those are the ideas that spring into my mind. It is impossible to "rewind" a `Scanner`. – Turing85 Dec 28 '16 at 16:42
  • 1
    You don't want to read the file twice, so don't use an array, and you almost certainly don't want to read an entire file into memory in the first place. Practically any text file can be processed one line at a time, or a character at a time. – user207421 Dec 28 '16 at 16:54
  • Possible duplicate of [Number of lines in a file in Java](http://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java) – wake-0 Dec 28 '16 at 16:58

4 Answers4

4

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[]{});
Naghaveer R
  • 2,890
  • 4
  • 30
  • 52
2

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.

GuiSim
  • 7,361
  • 6
  • 40
  • 50
0

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];
ItamarG3
  • 4,092
  • 6
  • 31
  • 44
  • Your suggestion for `BufferedReader` makes me wonder if you understand OPs intentation no to read the whole file just to get the line count. – Tom Dec 28 '16 at 16:47
  • @Tom I didn't think about that. but if the file has **very** long lines, then you would need a `BufferedReader`. Still, I updated my answer accordingly. – ItamarG3 Dec 28 '16 at 16:48
  • It doesn't matter if you use `BufferedReader`, `FileReader` or `Scanner`, the whole idea of reading the complete file to get the line count for an array and then read the file again later is nonsense. That's why OP asked for a better way and Collections are one. – Tom Dec 28 '16 at 16:55
  • @Tom Oh. my mistake. I misunderstood the question :P – ItamarG3 Dec 28 '16 at 16:57
  • I would wait with an answer anyway. In order to answer this properly one should know what OPs goal is. Why he needs an array and what he tries to do with the file and its content. So OP should answer that first, then one can write some ways to achieve his goal. – Tom Dec 28 '16 at 16:59
0

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.

Tahir Hussain Mir
  • 2,506
  • 2
  • 19
  • 26