[Q#36110478][A#36110491] How can I get specific data element in a text file
https://stackoverflow.com/q/36110478
I have a text file and two columns in it(name and birthday). And in first column I have two names(john and brayn). I only want to get name brayn and his birthday. How can I do this? my text file: name birthday john 1991 brayn 1994 Below the code snippet that I tried: Only want to get brayn's row in the text file and assign it to variable.
Answer
https://stackoverflow.com/a/36110491
Assuming each line will always have the format in your sample data above, then you can simply split each line of the text file and retain the second string: Output:
APIzation
String line = "name: brayn birthday: 1994";
String[] parts = line.split(" ");
String name = parts[1];
System.out.println(name);
brayn
package com.stackoverflow.api;
public class Human36110491 {
public static String getNameFromLine(String line) {
String[] parts = line.split(" ");
String name = parts[1];
//System.out.println(name);
return name;
}
}
package com.stackoverflow.api;
/**
* How can I get specific data element in a text file
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/36110491">https://stackoverflow.com/a/36110491</a>
*/
public class APIzator36110491 {
public static String getElement(String line) throws Exception {
String[] parts = line.split(" ");
String name = parts[1];
return name;
}
}