How to read only integers from a file in java? Suppose the file has something like this:
(14,2,3),(2,3,4)
(2,6,78)
Now I want to read only the integers not the brackets and commas.How do I do it?

You are going to need to open the file for reading. read all the lines and do some parsing on it. Post what you have so far and people may be more willing to help.

Use the Scanner class. There are tons of different ways you can do this with the methods in there, some involving regular expressions/Pattern, some with only the basic Scanner methods.

Member Avatar for ztini
import java.io.BufferedReader;


public class IntegerReader {
	public static void main(String[] args) {
		
		BufferedReader br = Utility.openFile("src/integer.txt");
		String line;
		
		while ((line = Utility.readLine(br)) != null) {
			for (char letter : line.toCharArray()) {
				if (letter >= '0' && letter <= '9')
					System.out.print(letter + " ");
			}
			System.out.println();
		}		
	}
}

You don't necessarily need to write a Utility class...just open the file and read from it how you see fit. Remember that chars are essentially integers from which you can invoke integer logic on them.


Anyway, here is what I use as a Utility class. Feel free to use it as you see fit.

import java.io.BufferedReader;
import java.io.FileReader;


public class Utility {
	
	public static BufferedReader openFile(String filename) {
		try { return new BufferedReader(new FileReader(filename)); }
		catch (IOException e) { return null; }
	}
	
	public static void closeFile(BufferedReader reader) {
		try { reader.close(); }
		catch (IOException e) { } 
	}
	
	public static String readLine(BufferedReader reader) {
		try { return reader.readLine(); } 
		catch (IOException e) { return null; }
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.