Java,用冒号分割输入文件

我想在冒号字符的java中拆分一些字符串。

字符串的格式为: Account:Password

我想分开令牌: AccountPassword 。 最好的方法是什么?

请先看看Ernest Friedman-Hill的回答。

 String namepass[] = strLine.split(":"); String name = namepass[0]; String pass = namepass[1]; // do whatever you want with 'name' and 'pass' 

不确定你需要帮助的部分,但请注意上面的split()调用永远不会返回除单个元素数组以外的任何内容,因为根据定义, readLine()在看到\n字符时会停止。 另一方面, split(":")对你来说应该非常方便……

你需要使用split(“:”)。 试试这个-

 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 accountsList = new ArrayList(); String splitValues[] = input.split(":"); Account account = new Account(splitValues[0], splitValues[1]); accountsList.add(account); } //perform your operations with accountList } } 

希望能帮助到你!