سؤال

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("");
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

If you know the fourth word in each line is supposed to be the version number just grab that word and get the first character. If its not necessarily the fourth word try using indexOf() on the line and then get the character before that, that is if you know for sure each line is set up this way.

I meant to say if each line is known to have the format you showed above you should be able to use IndexOf() on the decimal.

AAAAAA B Version 5(.)0.1

Or use split() to split white space and get each word

parts = line.split(" ");
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(Your string here);

if(m.find()) {
    System.out.println(m.group());
}

It tries to find a negative or positive integer and prints it if it can find any.

Well, first of all, make sure that you post your full code. It's much easier to diagnose the problem when you actually have the information along-side it. Secondly, what you're going to want is a scanner that's declared to read this .txt file.

A regular scanner is delcared like this:

Scanner sc = new Scanner(System.in);

This will read the system imput for your own file. however, you could change system.in to your file if you declare the file as a variable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top