Java, separating input file with colons
I want to split some lines in java by colon character.
Strings format Account:Password
.
I want to split the tokens: Account
and Password
. What's the best way to do this?
First, answer the question from Ernest Friedman-Hill.
String namepass[] = strLine.split(":");
String name = namepass[0];
String pass = namepass[1];
// do whatever you want with 'name' and 'pass'
Not sure what part you need help on, but note that the call split()
in the above example will never return anything other than a singleton array, as it readLine()
stops by definition when it sees a \n
character. split(":")
, on the other hand, should be very convenient for you ...
You need to use split (":"). Try it -
import java.util.ArrayList;
import java.util.List;
class Account {
String username;
String password;
public Account(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
class Solution {
public static void main(String[] args) {
while(.....){//read till the end of the file
String input = //each line
List<Account> accountsList = new ArrayList<Account>();
String splitValues[] = input.split(":");
Account account = new Account(splitValues[0], splitValues[1]);
accountsList.add(account);
}
//perform your operations with accountList
}
}
Hope it helps!