'how to get a number from a file
I have to get a number from a file, some files have letters and numbers convined. like (dsh8kuebw9) or have spaces like(8 8) how can I get those numbers? I have tried so many times. I have a method to find the occurences of a digit is in a number is the count8 method.
The parseInt converts the line of the file in a integer but because in some files there are letters I am having trouble with my method because it only accepts integers no Strings
File file_a = new File("C:\\name\\textFile8a.txt");
try
{
FileReader in = new FileReader(file_a);
BufferedReader readFile = new BufferedReader(in);
String n = readFile.readLine();
int num = Integer.parseInt(n);
System.out.println(count8(num, 8));
}
catch(IOException e)
{
System.out.println("file could not be founded");
System.err.println("OIException: " + e.getMessage());
}
Solution 1:[1]
You can remove all the numbers in your string before you parse it by replacing non-numberic characters with an empty string:
String n = readFile.readLine();
n = n.replaceAll("[^0-9]", "");
int num = Integer.parseInt(n);
Solution 2:[2]
basic and simple solution
public static ArrayList<Integer> extractNumber(String s) {
ArrayList returnList = new ArrayList<Integer>();
Pattern regex = Pattern.compile("\\d[\\d.]*");
Matcher matcher = regex.matcher(s);
while (matcher.find()) {
returnList.add(matcher.group());
}
return returnList;
}
public static void main(String[] args) {
File file_a = new File("C:\\name\\textFile8a.txt");
try {
FileReader in = new FileReader(file_a);
BufferedReader readFile = new BufferedReader(in);
String n = readFile.readLine();
ArrayList<Integer> numberList = extractNumber(n);
System.out.println(numberList);
} catch (IOException e) {
System.out.println("file could not be founded");
System.err.println("OIException: " + e.getMessage());
}
}
Solution 3:[3]
Below is a method which will extract any signed or unsigned, Whole or Floating Point, numerical values from a supplied Input String of any length and return those values within a String[] Array. Read the method JavaDoc and the comments within the method:
/**
* This method will extract all signed or unsigned Whole or floating point
* numbers from a supplied String. The numbers extracted are placed into a
* String[] array in the order of occurrence and returned.<br><br>
*
* It doesn't matter if the numbers within the supplied String have leading
* or trailing non-numerical (alpha) characters attached to them.<br><br>
*
* A Locale can also be optionally supplied so to use whatever decimal symbol
* that is desired otherwise, the decimal symbol for the system's current
* default locale is used.
*
* @param inputString (String) The supplied string to extract all the numbers
* from.<br>
*
* @param desiredLocale (Optional - Locale varArgs) If a locale is desired for a
* specific decimal symbol then that locale can be optionally
* supplied here. Only one Locale argument is expected and used
* if supplied.<br>
*
* @return (String[] Array) A String[] array is returned with each element of
* that array containing a number extracted from the supplied
* Input String in the order of occurrence. If the supplied Input
* String was found to be null or empty then a 0 length String[]
* Array is returned.
*/
public static String[] getNumbersFromString(String inputString, java.util.Locale... desiredLocale) {
if (inputString == null || inputString.isEmpty()) {
return new String[] {}; // Return a 0 length String Array.
}
// Get the decimal symbol the the current system's locale.
char decimalSeparator = new java.text.DecimalFormatSymbols().getDecimalSeparator();
/* Is there a supplied Locale? If so, set the decimal
separator to that for the supplied locale */
if (desiredLocale != null && desiredLocale.length > 0) {
decimalSeparator = new java.text.DecimalFormatSymbols(desiredLocale[0]).getDecimalSeparator();
}
/* The first replaceAll() removes all dashes (-) that are preceeded
or followed by whitespaces. The second replaceAll() removes all
periods from the input string except those that part of a floating
point number. The third replaceAll() removes everything else except
the actual numbers. */
return inputString.replaceAll("\\s*\\-\\s{1,}","")
.replaceAll("\\.(??)", "")
.replaceAll("[^-?\\d+" + decimalSeparator + "\\d+]", " ")
.trim().split("\\s+");
}
How you might use this method:
String filePath = "C:/name/textFile8a.txt";
String[] numbersArray = {};
// Get the decimal character used in the current System.
char decimalSeparator = new java.text.DecimalFormatSymbols().getDecimalSeparator();
// 'Try With Resources' used to to auto-close the reader and free resources.
try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(filePath))) {
String line;
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
lineCounter++;
System.out.println("File Line #" + lineCounter + " contains:");
System.out.println("======================");
line = line.trim();
// Skip blank lines (if any).
if (line.isEmpty()) {
continue;
}
numbersArray = getNumbersFromString(line); // ****
/* Print the number(s) extracted from the file line
to the Console Window... */
for (String strgValue : numbersArray) {
// Do what you want with the numerical values, for example:
// Is this particular number a floating point value?
if (strgValue.contains(Character.toString(decimalSeparator))) {
// Yes it is...
double dblValue = Double.parseDouble(strgValue);
System.out.println("Extracted: -> " + dblValue);
}
else {
//Nope..so it must be a Integer.
int intValue = Integer.parseInt(strgValue);
System.out.println("Extracted: -> " + intValue);
}
// Or just print them all out...
// System.out.println(strgValue);
}
System.out.println();
}
}
catch (FileNotFoundException ex) {
System.out.println("File could not be found!");
}
catch (IOException ex) {
System.err.println("OIException: -> " + ex.getMessage());
}
If the text file contained:
This is the #1 line.
This is version2.45 of the 2nd line
abcd4256.4efgha67klmn-56.2opqr-12stuvw666.78.
777 535 55 88 999
-56.765
dsh8kuebw9
and you run this file through the above code, the Console Window will display:
File Line #1 contains:
======================
Extracted: -> 1
File Line #2 contains:
======================
Extracted: -> 2.45
Extracted: -> 2
File Line #3 contains:
======================
Extracted: -> 4256.4
Extracted: -> 67
Extracted: -> -56.2
Extracted: -> -12
Extracted: -> 666.78
File Line #4 contains:
======================
Extracted: -> 777
Extracted: -> 535
Extracted: -> 55
Extracted: -> 88
Extracted: -> 999
File Line #5 contains:
======================
Extracted: -> -56.765
File Line #6 contains:
======================
Extracted: -> 8
Extracted: -> 9
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Watson |
| Solution 2 | Vasim Hayat |
| Solution 3 | DevilsHnd |
