Search code examples
javatextbufferedreaderfilereader

Finding the first number of a .txt file - Java


I have different .txt files, which should be read by Java. Then java should give me the first number of first line or if I say differently, the first number of 4th word.

For instance:

"AAAAAA B Version 5.0.1" or "AAAAAA B Version 6.0.2"

5 or 6 should be the resulting number.

I've tried some methods such as bufferedReader with line.charAt but I don't know how I can make it work for my problem. What would you guys suggest ?

BufferedReader br = null;
br = new BufferedReader(new FileReader(new File("C:\\Users\\Desktop\\new2.txt")));
String line = null;
while((line = br.readLine()) != null) {
    String[] parts = line.startsWith(...?.); 
    System.out.println("");

Solution

  • First of all just read First line of the file.

    File f=new File("your_file.txt");
    FileReader fr=new FileReader(f);
    BufferedReader br=new BufferedReader(fr);
    String firstLine=br.readLine();
    

    Then split the line by spaces to get String array of words

    String[] words=firstLine.split("\\s+");
    

    Split the fourth word using " . "

    String[] nos=words[3].split("\\.");
        System.out.println(nos[0]);//Expected output, First number of fourth 
    //word in first line of given file