I have assignment that requires us to read from a text file of covid 19 codon sequences. I have read in the first line as a string. I am able to convert this one line into 3 character substrings. However, my issue is now to do this for the rest of the file. When I add a hasNext method, it doesn't seem to work the same as my testline.
{
//Open the file
File file = new File("D://Downloads/covid19sequence.txt");
Scanner scan = new Scanner(file); String testLine = ""; String contents = ""; String codon2 = "";
double aTotal, lTotal, lPercentage;
ArrayList<String> codonList = new ArrayList<String>();
//Read a line in from the file and assign codons via substring
testLine = scan.nextLine();
for (int i = 0; i < testLine.length(); i += 3)
{
String codon = testLine.substring(i, i + 3);
codonList.add(codon);
}
while(scan.hasNext())
System.out.println(codonList);
}
For reference here is the output for the testline:
[AGA, TCT, GTT, CTC, TAA, ACG, AAC, TTT, AAA, ATC, TGT, GTG, GCT, GTC, ACT, CGG, CTG, CAT, GCT, TAG]
Use while(scan.hasNextLine()) to go through text file, you may do it like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Codons {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D://Downloads/covid19sequence.txt");
Scanner scan = new Scanner(file); String testLine = ""; String contents = ""; String codon2 = "";
double aTotal, lTotal, lPercentage;
ArrayList<String> codonList = new ArrayList<String>();
//Read a line in from the file and assign codons via substring
while(scan.hasNextLine()) {
testLine = scan.nextLine();
for (int i = 0; i < testLine.length(); i += 3)
{
String codon = testLine.substring(i, i + 3);
codonList.add(codon);
}
}
scan.close();
System.out.println(codonList);
}
}
If a Scanner is used it may be better to implement a separate method reading the contents using the scanner line by line and splitting the line into 3-character chunks as suggested here:
static List<String> readCodons(Scanner input) {
List<String> codons = new ArrayList();
while (input.hasNextLine()) {
String line = input.nextLine();
Collections.addAll(codons, line.split("(?<=\\G...)"));
}
return codons;
}
Test (using Scanner on the basis of a multiline String):
// each line contains 20 codons
String contents = "AGATCTGTTCTCTAAACGAACTTTAAAATCTGTGTGGCTGTCACTCGGCTGCATGCTTAG\n"
+ "GATCTGTTCTCTAAACGAACTTTAAAATCTGTGTGGCTGTCACTCGGCTGCATGCTTAGA\n"
+ "ATCTGTTCTCTAAACGAACTTTAAAATCTGTGTGGCTGTCACTCGGCTGCATGCTTAGAG\n";
List<String> codons = readCodons(new Scanner(contents));
for (int i = 0; i < codons.size(); i++) {
if (i > 0 && i % 10 == 0) {
System.out.println();
}
System.out.print(codons.get(i) + " ");
}
Output
AGA TCT GTT CTC TAA ACG AAC TTT AAA ATC
TGT GTG GCT GTC ACT CGG CTG CAT GCT TAG
GAT CTG TTC TCT AAA CGA ACT TTA AAA TCT
GTG TGG CTG TCA CTC GGC TGC ATG CTT AGA
ATC TGT TCT CTA AAC GAA CTT TAA AAT CTG
TGT GGC TGT CAC TCG GCT GCA TGC TTA GAG
Similar results should be provided if a scanner is created on a text file:
try (Scanner input = new Scanner(new File("codons.data"))) {
List<String> codons = readCodons(input);
// print/process codons
}
Related
import java.io.*;
import java.util.*;
class A {
public static void main(String args[]) throws Exception {
Console con = System.console();
String str;
int i=0;
HashMap map = new HashMap();
HashSet set = new HashSet();
System.out.println("Enter File Name : ");
str = con.readLine();
File f = new File(str);
f.createNewFile();
FileInputStream fis = new FileInputStream(str);
StreamTokenizer st = new StreamTokenizer(fis);
while(st.nextToken()!=StreamTokenizer.TT_EOF) {
String s;
switch(st.ttype) {
case StreamTokenizer.TT_NUMBER: s = st.nval+"";
break;
case StreamTokenizer.TT_WORD: s = st.sval;
break;
default: s = ""+((char)st.ttype);
}
map.put(i+"",s);
set.add(s);
i++;
}
Iterator iter = set.iterator();
System.out.println("Frequency Of Words :");
while(iter.hasNext()) {
String word;
int count=0;
word=(String)iter.next();
for(int j=0; j<i ; j++) {
String word2;
word2=(String)map.get(j+"");
if(word.equals(word2))
count++;
}
System.out.println(" WORD : "+ word+" = "+count);
}
System.out.println("Total Words In Files: "+i);
}
}
In This code First I have already created a text file which contains the following data :
# Hello Hii World # * c++ java salesforce
And the output of this code is :
**Frequency Of Words :
WORD : # = 1
WORD : # = 1
WORD : c = 1
WORD : salesforce = 1
WORD : * = 1
WORD : Hii = 1
WORD : + = 2
WORD : java = 1
WORD : World = 1
WORD : Hello = 1
Total Words In Files: 11**
where i am unable to find why this shows c++ as a seperate words . I
want to combine c++ as a single word as in the output
You can do it in this way
// Create the file at path specified in the String str
// ...
HashMap<String, Integer> map = new HashMap<>();
InputStream fis = new FileInputStream(str);
Reader bufferedReader = new BufferedReader(new InputStreamReader(fis));
StreamTokenizer st = new StreamTokenizer(bufferedReader);
st.wordChars('+', '+');
while(st.nextToken() != StreamTokenizer.TT_EOF) {
String s;
switch(st.ttype) {
case StreamTokenizer.TT_NUMBER:
s = String.valueOf(st.nval);
break;
case StreamTokenizer.TT_WORD:
s = st.sval;
break;
default:
s = String.valueOf((char)st.ttype);
}
Integer val = map.get(s);
if(val == null)
val = 1;
else
val++;
map.put(s, val);
}
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
System.out.println("Frequency Of Words :");
int sum = 0;
while(iter.hasNext()) {
String word = iter.next();
int count = map.get(word);
sum += count;
System.out.println(" WORD : " + word + " = " + count);
}
System.out.println("Total Words In Files: " + sum);
Note that I've updated your code using Generics instead of the raw version of HashMap and Iterator. Moreover, the constructor you used for StreamTokenizer was deprecated. The use of both map and set was useless because you can iterate over the key set of the map using .keySet() method. The map now goes from String (the word) to Integer (the number of word count).
Anyway, regarding the example you did, I think that a simple split method would have been more appropriate.
For further information about the wordChars method of StreamTokenizer you can give a look at #wordChars(int, int)
Use Scanner and File to read this file of vocabulary scores as measured by the General Social Survey from 1972 to 2004. Compute and display the mean score for both males and females.
I am unsure of how to seperate the lines into chunks by comma and to still retain the correct data.
Example of what the file contains:
Female,7
Male,3
Male,6
Male,10
Female,10
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.csv");
Scanner in = new Scanner(file);
String run = "";
int maleCount = 0;
int femaleCount = 0;
int maleScore = 0;
int femaleScore = 0;
while (in.hasNextLine()) {
String current = in.nextLine();
in.useDelimiter(",");
if (current.contains("f")) {
femaleCount++;
// add score onto femaleScore
}
else {
maleCount++;
// add score onto maleScore
}
double femaleAverage = femaleScore / femaleCount;
System.out.println(femaleAverage);
double maleAverage = maleScore / maleCount;
System.out.println(maleAverage);
}
in.close();
}
Your calculation was inside the while loop, meaning it would calculate this average once per line in the file, which is wrong.
The code below assumes the format of the data is the same as stated in your post.
Female,7
Male,3
Male,6
Male,10
Female,10
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.csv");
Scanner in = new Scanner(file);
String run = "";
int maleCount = 0;
int femaleCount = 0;
int maleScore = 0;
int femaleScore = 0;
while (in.hasNextLine()) {
String current = in.nextLine();
String[] split = current.split(",");
if (split[0].toLowerCase().contains("f")) {
femaleCount++;
femaleScore += Integer.parseInt(split[1]);
// add score onto femaleScore
} else {
maleCount++;
maleScore += Integer.parseInt(split[1]);
// add score onto maleScore
}
}
double femaleAverage = femaleScore / femaleCount;
System.out.println(femaleAverage);
double maleAverage = maleScore / maleCount;
System.out.println(maleAverage);
in.close();
}
If the data is different, post it here and I will edit the code accordingly
Assuming your input file is structured as below:
male, 4
female, 7
male, 3
female, 5
etc
Then the below code should do what you want. You were pretty close, just had to split the line's on commas and then assess the parts (gender/score) like array.
String filePath = "C:\\Users\\adam\\Documents\\Scores.txt";
File file = new File(filePath);
Scanner scanner = new Scanner(file);
int maleCount = 0;
int femaleCount = 0;
int maleScore= 0;
int femaleScore = 0;
while(scanner.hasNext()){
String line = scanner.nextLine();
String[] split = line.split(",");
String gender = split[0];
String score = split[1];
if(gender.toLowerCase().trim().equals("male")){
maleCount++;
maleScore += Integer.valueOf(score.trim());
}else if(gender.toLowerCase().trim().equals("female")){
femaleCount++;
femaleScore += Integer.valueOf(score.trim());
}
}
scanner.close();
double maleAverage = (double) maleScore / maleCount;
double femaleAverage = (double) femaleScore / femaleCount;
System.out.println("Male Average: " + maleAverage);
System.out.println("Female Average: " + femaleAverage);
I'm creating a program which reads the contents of a .txt file, it validates and then outputs the contents of that file in a nice formatted table. My program currently reads the file and then outputs the content, I'm trying to implement the validation of said file content.
I'll now explain the way my program reads the file:
The .txt contents:
firstname lastname
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
The txt file contains data in this format:
{gamename} : {gamescore} : {minutesplayed}
To read the .txt I use:
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
To then split the data I use this for loop on each letter from a-to-g as shown below:
//~~~~a-line-split~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
To clarify by validation I need to inform the user if data is missing from a line for example if line one had:
gameone : {missing} : 1428
currently I have this simple if statement for each line:
if (bline.length < 3)
{
System.out.println("There is an error in row one!");
}
However I need to the program to know exactly where on each line the data is missing. Not just a generic response of:
System.out.println("There is an error in row one!");
But instead something along the lines of:
System.out.println("There is data missing, row: 1 column: 2");
Full code as requested:
package readfile;
import java.io.*;
import java.util.*;
public class readfile
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String FileN = " ";
String a = " ";
String b = " ";
String c = " ";
String d = " ";
String e = " ";
String f = " ";
String g = " ";
boolean fileExists = false;
File newFile = null;
while(!fileExists)
{
System.out.println("Enter the name of the file you want to open: ");
FileN = scan.nextLine();
newFile = new File(FileN);
fileExists = newFile.exists();
if (!fileExists)
{
System.out.println(FileN + " not found...");
}
}
try {
Scanner scan2;
scan = new Scanner(newFile);
}
catch(FileNotFoundException fnfe) {
System.out.println("sorry but the file doesn't seem to exist");
}
//++++++++++++++=FILE READ=++++++++++++++++++++
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
while(scan.hasNext())
{
a = scan.nextLine();
b = scan.nextLine();
c = scan.nextLine();
d = scan.nextLine();
e = scan.nextLine();
f = scan.nextLine();
g = scan.nextLine();
}
//+++++++++++++++ARRAYS FOR THE LINES+++++++++++++++++++
//~~~~A-LINE~~~~//
String[] aline;
aline = a.split(":");
for (int i=0; i<aline.length; i++)
{
aline[i] = aline[i].trim();
//System.out.println(aline[i]);
}
//~~~~B-LINE~~~~//
String[] bline;
bline = b.split(":");
for (int i=0; i<bline.length; i++)
{
bline[i] = bline[i].trim();
//System.out.println(bline[i]);
}
//~~~~C-LINE~~~~//
String[] cline;
cline = c.split(":");
for (int i=0; i<cline.length; i++)
{
cline[i] = cline[i].trim();
//System.out.println(cline[i]);
}
//~~~~D-LINE~~~~//
String[] dline;
dline = d.split(":");
for (int i=0; i<dline.length; i++)
{
dline[i] = dline[i].trim();
//System.out.println(dline[i]);
}
//~~~~e-LINE~~~~//
String[] eline;
eline = e.split(":");
for (int i=0; i<eline.length; i++)
{
eline[i] = eline[i].trim();
//System.out.println(eline[i]);
}
//~~~~f-LINE~~~~//
String[] fline;
fline = f.split(":");
for (int i=0; i<fline.length; i++)
{
fline[i] = fline[i].trim();
//System.out.println(fline[i]);
}
//~~~~g-LINE~~~~//
String[] gline;
gline = g.split(":");
for (int i=0; i<gline.length; i++)
{
gline[i] = gline[i].trim();
//System.out.println(gline[i]);
}
String user = aline [0];
//~~~~~~~~~GAME NAMES~~~~~~~~~~~~~//
//GTA
String gameone = bline [0];
//MINECRAFT
String gametwo = cline [0];
//ASSASSIN'S CREED IV
String gamethree = dline [0];
//PAYDAY2
String gamefour = eline [0];
//WOLFENSTEIN
String gamefive = fline [0];
//FARCRY 4
String gamesix = gline [0];
//~~~~~~~~~~Achievement Score~~~~~~~~~~~~//
//GTA SCORE
String scoreone = bline [1];
//MINECRAFT SCORE
String scoretwo = cline [1];
//ASSASSIN'S CREED IV SCORE
String scorethree = dline [1];
//PAYDAY2 SCORE
String scorefour = eline [1];
//WOLFENSTEIN SCORE
String scorefive = fline [1];
//FARCRY 4 SCORE
String scoresix = gline [1];
//+++++++++++++++++++++TOTAL~~CALC++++++++++++++++++++++//
double totalcount = 79.566; // change to the amount played.
int totalhours = (int)totalcount;
int totalmin = (int)(totalcount*60)%60;
int totalsec = (int)(totalcount*(60*60))%60;
System.out.println("TOTAL TIME PLAYED:");
System.out.println(String.format("%s(hours) %s(minutes) %s(seconds)",
totalhours, totalmin, totalsec));
//~~~~~~~~~~Minutes Played~~~~~~~~~~~~//
//GTA min
String minone = bline [2];
//MINECRAFT min
String mintwo = cline [2];
//ASSASSIN'S CREED IV min
String minthree = dline [2];
//PAYDAY2 min
String minfour = eline [2];
//WOLFENSTEIN min
String minfive = fline [2];
//FARCRY 4 min
String minsix = gline [2];
//~~~~~~~~~GAMES TEST~~~~~~~~~~~~//
System.out.println("\nUSER: "+user);
System.out.println("\nDATA: ");
System.out.println("1: "+gameone+" | score: "+scoreone+"
| minutes played: "+minone);
System.out.println("2: "+gametwo+" | score: "+scoretwo+"
| minutes played: "+mintwo);
System.out.println("3: "+gamethree+" | score: "+scorethree+"
| minutes played: "+minthree);
System.out.println("4: "+gamefour+" | score:
"+scorefour+" | minutes played: "+minfour);
System.out.println("5: "+gamefive+" | score: "+scorefive+"
| minutes played: "+minfive);
System.out.println("6: "+gamesix+" | score: "+scoresix+"
| minutes played: "+minsix);
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two
column "+(i+1));
}
}
}
}
}
if (bline.length < 3)
{
int column = 0;
for(int i = 0; i<bline.length; i++){
column = i;
if(bline[i] == null || bline[i].trim() == ""){
System.out.println("There is an error in row two column "+(i+1));
}
}
}
Didn't test this but it should work
EDIT:
Looking at your full code bline[2], cline[2]... and so on will give you an Index Out of bounds exception if those values are missing from the file in the first place so before making that call you should do a check first you can create a static method to do the check
public static String getAtIndex(String[] array, int indexToCkeck){
if(indexToCkeck >=array.length){
return "";
}
else{
return array[indexToCkeck];
}
}
So instead of doing bline[2], cline[2] ... use readfile.getAtIndex(bline, 2) so this way if the info is missing it will return an empty string
Also not tested, should be fine though
Use a well tested library like supercsv or any other. This will save you some hours as soon as your text format gets more complex. It also provides a good set of build-in data types to be used to validate each single column of your data. Also you can map the data directly to a POJO which can be handy in some situations.
To load just each row into a map you could do the following:
Prepare your file in stack47220687.txt:
Gamename: Gamescore: Minutestoplay
Gameone : 120 : 1428
Gametwo : 20 : 10
Gamethree : 90 : 800
Gamefour : 190 : 2001
Gamefive : 25 : 80
Gamesix : 55 : 862
And use something like this
package stack47220687;
import java.io.FileReader;
import java.util.Map;
import org.junit.Test;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.prefs.CsvPreference;
public class HowToReadACSVFile {
private static final CsvPreference COLON_DELIMITED = new CsvPreference.Builder('"', ':', "\n").build();
private static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // gamename
new NotNull(), // gamescore
new NotNull(), // minutestoplay
};
return processors;
}
#Test
public void read() throws Exception {
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(
Thread.currentThread().getContextClassLoader().getResource("stack47220687.txt").getPath()),
COLON_DELIMITED);
// the header columns are used as the keys to the Map
final String[] header = mapReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
Map<String, Object> oneRecordInAMap;
while ((oneRecordInAMap = mapReader.read(header, processors)) != null) {
System.out.println(String.format("lineNo=%s, rowNo=%s, this line stored in a map=%s",
mapReader.getLineNumber(), mapReader.getRowNumber(), oneRecordInAMap));
/**
* oneRecordInAMap.get("Gamescore");
*/
}
} finally {
if (mapReader != null) {
mapReader.close();
}
}
}
}
works with super-csv 2.4.0
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>
and will print
lineNo=2, rowNo=2, this line stored in a map={ Gamescore= 120 , Gamename=Gameone , Minutestoplay= 1428 }
lineNo=3, rowNo=3, this line stored in a map={ Gamescore= 20 , Gamename=Gametwo , Minutestoplay= 10 }
lineNo=4, rowNo=4, this line stored in a map={ Gamescore= 90 , Gamename=Gamethree , Minutestoplay= 800 }
lineNo=5, rowNo=5, this line stored in a map={ Gamescore= 190 , Gamename=Gamefour , Minutestoplay= 2001 }
lineNo=6, rowNo=6, this line stored in a map={ Gamescore= 25 , Gamename=Gamefive , Minutestoplay= 80 }
lineNo=7, rowNo=7, this line stored in a map={ Gamescore= 55 , Gamename=Gamesix , Minutestoplay= 862}
It will also provide meaningful error messages if your format is not correct.
I am trying to open two text files and find similar lines in them.
My code is correctly reading all the lines from both the text files.
I have used nested for loops to compare line1 of first text file with all lines of second text file and so on.
However, it is only detecting similar lines which have same line number,
(eg. line 1 of txt1 is cc cc cc and line 1 of txt2 is cc cc cc, then it correctly finds and prints it),
but it doesn't detect same lines on different line numbers in those files.
import java.io.*;
import java.util.*;
public class FeatureSelection500 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
File f1 = new File("E://implementation1/practise/ComUpdatusPS.exe.hex-04-ngrams-Freq.txt");
File f2 = new File("E://implementation1/practise/top-300features.txt");
Scanner scan1 = new Scanner(f1);
Scanner scan2 = new Scanner(f2);
int i = 1;
List<String> txtFileOne = new ArrayList<String>();
List<String> txtFileTwo = new ArrayList<String>();
while (scan1.hasNext()) {
txtFileOne.add(scan1.nextLine());
}
while (scan2.hasNext())
{
txtFileTwo.add(scan2.nextLine());
}
/*
for(String ot : txtFileTwo )
{
for (String outPut : txtFileOne)
{
// if (txtFileTwo.contains(outPut))
if(outPut.equals(ot))
{
System.out.print(i + " ");
System.out.println(outPut);
i++;
}
}
}
*/
for (int j = 0; j < txtFileTwo.size(); j++) {
String fsl = txtFileTwo.get(j);
// System.out.println(fileContentSingleLine);
for (int z = 0; z < 600; z++) // z < txtFileOne.size()
{
String s = txtFileOne.get(z);
// System.out.println(fsl+"\t \t"+ s);
if (fsl.equals(s)) {
System.out.println(fsl + "\t \t" + s);
// my line
// System.out.println(fsl);
} else {
continue;
}
}
}
}
}
I made your code look nicer, you're welcome :)
Anyway, I don't understand that you get that bug. It runs through all of the list2 for every line in the list1...
import java.io.*;
import java.util.*;
public class FeatureSelection500 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
File file1 = new File("E://implementation1/practise/ComUpdatusPS.exe.hex-04-ngrams-Freq.txt");
File file2 = new File("E://implementation1/practise/top-300features.txt");
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
List<String> txtFile1 = new ArrayList<String>();
List<String> txtFile2 = new ArrayList<String>();
while (scan1.hasNext()) {
txtFile1.add(scan1.nextLine());
}
while (scan2.hasNext()) {
txtFile2.add(scan2.nextLine());
}
for (int i = 0; i < txtFile2.size(); i++) {
String lineI = txtFile2.get(i);
// System.out.println(fileContentSingleLine);
for (int j = 0; j < txtFile1.size(); j++){ // z < txtFileOne.size(
String lineJ = txtFile1.get(j);
// System.out.println(fsl+"\t \t"+ s);
if (lineI.equals(lineJ)) {
System.out.println(lineI + "\t \t" + lineJ);
// my line
// System.out.println(fsl);
}
}
}
}
}
I don't see any problem with your code. Even the block you commented is absolutely fine. Since, you are doing equals() you should make sure that you have same text (same case) in the two files for them to be able to satisfy the condition successfully.
for(String ot : txtFileTwo )
{
for (String outPut : txtFileOne)
{
if(outPut.equals(ot)) /* Check Here */
{
/* Please note that here i will not give you line number,
it will just tell you the number of matches in the two files */
System.out.print(i + " ");
System.out.println(outPut);
i++;
}
}
}
I have a text file which has details like date,time,phone number, etc. I am trying to retrieve these details using the java indexOf concept. However, the digits in the phone number would change depending on the type of call.
How can I improve the code so I am able to retrieve every phone number from the file. Here's what I've been trying :
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String getIndex="";
while ((line = reader.readLine()) != null) {
line = line.replaceAll("[\\s]+", " "); //remove all large spaces from the file.
/*
the dialledNo is chosen with the help of a combo box.
calculating the start and end index in order to print the dialled no.
*/
int startIndex = getIndex.indexOf(dialledNo);
int endIndex = getIndex.indexOf(" ", startIndex);
strDialedNo= (startIndex + "," + endIndex);
And the code to retrieve the number is mentioned below :
String[] arrDialedNo = strDialedNo.split(",");
int DialedNoStart = Integer.parseInt(arrDialedNo[0]);
int DialedNoEnd = Integer.parseInt(arrDialedNo[1]);
DialedNo = line.substring(DialedNoStart, DialedNoEnd);
This is how my text file looks like:
0356 524 000 8861205063 12/03 18:59 00:08 01:20
0357 524 000 9902926868 12/03 20:01
0373 511 000 09886863637 13/03 11:46 01:01 02:40 S
0376 504 000 9845014967 13/03 11:46 00:11 01:20
0382 508 000 04443923200 13/03 12:04 03:11 04:80 S
0411 516 000 8884103111 13/03 16:25 01:03 01:20
This should work,
String[] b = line.split(" ");
String phoneNumber = null;
for (String x : b) {
boolean z = false;
if (x.length() == 10) {
char[] c = x.toCharArray();
for (char g : c) {
if (Character.isDigit(g)) {
z = true;
} else {
z = false;
break;
}
}
} else {
z = false;
}
if (z) {
phoneNumber = x;
}
}
/* Easiest way to to retrieve Phone number from Text file using Java */
package TestProject.EndToEnd;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("//File//Path//");
List<Object> ph = new ArrayList<Object>();
Scanner scan = new Scanner(file);
while(scan.hasNext()) {
scan.next();
if(scan.hasNextBigInteger()) {
ph.add(scan.next());
}
}
for (int i = 0; i < ph.size(); i++) {
if(ph.get(i).toString().length()==10) {
System.out.println(ph.get(i));
}
}
}
}