文件里只有一句话,前面是文件取出的字符串,后面打印的是substring(8,i)截取后的字符串,为什么会出现两种情况?如下所示,
文件中的文字是"keyword="的格式写入的,但是截取字符串后却会多一个字符"=",百思不得其解。
主要代码是这样:👌🏻
List<Account> accounts = new ArrayList<>();
String words = "";
// String words = "keyword=wchat.com;微信;user=name44;password=845965*Zoo\r\n" +
// "keyword=wchat.com;微信;user=name44;password=77854530*Traggle";//若是编译期直接赋值无此种情况
words = FileEncode.readEncodeFile1("src/file/strategy1.txt");//用文件读取后words正常但是截取字符串结果错误
String[] lineWords = words.split("\n");
System.out.println("words:" + words);
for (int i = 0; i < lineWords.length; i++) {
int keyIndex = lineWords[i].lastIndexOf(";user=");
int userIndex = lineWords[i].lastIndexOf(";password=");
if (keyIndex != -1 && userIndex != -1) {
String keyword = lineWords[i].substring(8, keyIndex);//i=0时,截取后多了个=
String user = lineWords[i].substring(keyIndex + 6, userIndex);
String password = lineWords[i].substring(userIndex + 10);
Account account = new Account();
account.setKeyword(keyword);
account.setUser(user);
account.setPassword(password);
accounts.add(account);
} else {
System.out.println("找不到user和password");
}
}
for (Account a : accounts) {
System.out.println(a.toString());
}
估计是读文件导致出现问题
/**
* 读取文件 获取account列表 读取整个文件
* @param relative
* @param key 暂未使用
* @return
*/
public static String readEncodeFile1(String relative) {
File file = new File(relative);
FileInputStream fis = null;
String words = "";
try {
fis = new FileInputStream(file);
byte[] buf = new byte[1024]; //数据中转站 临时缓冲区 字节读取不会出现乱码
int length = 0;
while ((length = fis.read(buf)) != -1) {
words += new String(buf, 0, length);//将file中的内容遍历出来
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("找不到指定路径的文件:" + "" + relative);//项目的根路径不知道
} catch (IOException e) {
e.printStackTrace();
System.out.println("fis.read()异常");
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return words;
}
Account实体类:
public class Account {
private String keyword;//关键字
private String user;//账户名
private String password;//密码
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return "keyword=" + this.keyword +";user=" + this.user + ";password=" + this.password;
}
}