Noam Holin
Noam Holin

Reputation: 11

How to read only integers from file?

I got a problem when I'm trying to read int from text file. I'm using this kind of code

 import java.util.Scanner;
 import java.io.*;

 File  fileName =new File( "D:\\input.txt");
 try {
     Scanner in = new Scanner(fileName);
     c = in.nextInt();
     n = in.nextInt();

 } catch(Exception e){
       System.out.println("File not Found!!!");
 }        

If my text is edit like this

30
40

So it will work (meaning c=30, n=40). But if I want to edit the text file that will be like this

c=30
n=40

My code will not work.

How can I change my code to read only the numbers and ignore the "c=" and n=" or any others chars besides the numbers?

Upvotes: 0

Views: 6751

Answers (4)

winash
winash

Reputation: 511

If your data line will always be in the same format x=12345, use a regex to get the numeric value from the line

Upvotes: 0

Goran Štuc
Goran Štuc

Reputation: 581

you could read line by line(Scanner.nextLine) and check every character in the line by asking isDigit()

Upvotes: 0

Alexander
Alexander

Reputation: 23537

Following the format you want to use in the input file then it would be better if you make use of java.util.Properties. You won't need to care about the parsing.

Properties props = new Properties();
props.load(new FileInputStream(new File("D:\\input.txt")));
c = Integer.parseInt(props.getProperty("c"));
n = Integer.parseInt(props.getProperty("n"));

You can read more about the simple line-oriented format.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213223

You need to read your lines using Scanner.nextLine, split each line on =, and then convert the 2nd part to integer.

Remember to do the check - Scanner.hasNextLine before you read any line. So, you need to use a while loop to read each line.

A Simple implementation, you can extend it according to your need: -

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();

    String[] tokens = line.split("=");

    try {
        System.out.println(Integer.parseInt(tokens[1]);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
}

Now if you want to use those numbers later on, you can also add them in an ArrayList<Integer>.

Upvotes: 1

Related Questions