I want to parse numbers in a line of a text file line by line. For example, imagine _ as a space
my text file content looks like:
___34_______45
_12___1000
____4______167
...
I think you got the idea. Each line may have variable number of spaces separating the numbers, meaning there is no patte at all. The simplest solution could be read char by char and check if it is a number and go like that until the end of the number string and parse it. But there must be some other way. How can I read this in Java automatically so that I can get in a certain datastructure say array
Use java.util.Scaer. It has the nextInt() method, which does exactly what you want. I think you'll have to put them into an array "by hand".
import java.util.Scaer;
public class A {
public static void main(String[] args) {
Scaer in = new Scaer(System.in);
int v1 = in.nextInt(); //34
int v2 = in.nextInt(); //45
...
}
}
If you only need your numbers in a data structure, e.g. a flat array, then you can read the file with a Scaer and a simple loop. Scaer uses whitespace as the default delimiter, skipping multiple whitespaces.
Given List ints:
Scaer scan = new Scaer(file); // or pass an InputStream, String
while (scan.hasNext())
{
ints.add(scan.nextInt());
// ...
You'll need to handle exceptions on Scaer.nextInt.
But your proposed output data structure uses multiple arrays, one per line. You can read the file using Scaer.nextLine() to get individual lines as String. Then use String.split to split around whitespaces with a regex:
Scaer scan = new Scaer(file); // or InputStream
String line;
String[] strs;
while (scan.hasNextLine())
{
line = scan.nextLine();
// trim so that we get rid of leading whitespace, which will end
// up in strs as an empty string
strs = line.trim().split("\s+");
// convert strs to ints
}
You could also use a second Scaer to tokenize each individual line in an ier loop. Scaer will discard any leading whitespace for you, so you can leave off the trim.
Bum it old-school with BufferedReader and String's split() function:
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(inputFile));
String line;
while ((line = in.readLine()) != null) {
String[] inputLine = line.split("\s+");
// do something with your input array
}
} catch (Exception e) {
// error logging
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ignored) {}
}
}
(If you're using Java 7, the finally block is uecessary if you use the try-with-resources.)
This will change something like ______45___23 (where _ is whitespace) into an array ["45", "23"]. If you need those as integers, it's quite trivial to write a function to convert the String array into an int array:
public int[] convert(String[] s) {
int[] out = new int[s.length];
for (int i=0; i < out.length; i++) {
out[i] = Integer.parseInt(s[i]);
}
retu out;
}