How to read only integers from a file in java? Suppose the file has something like this:
Now I want to read only the integers not the brackets and commas.How do I do it?

7 Years
Discussion Span
Last Post by ztini

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.

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 + " ");

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; }

Edited by ztini: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.