gpt4 book ai didi

Java 将带有换行符的字符串拆分为数组,其中使用缓冲读取器从文件中读取字符串

转载 作者:行者123 更新时间:2023-12-01 11:31:20 27 4
gpt4 key购买 nike

我正在将文件加载到缓冲区中,该缓冲区又加载到字符串缓冲区中。然后我将此字符串缓冲区复制到字符串中。该字符串打印为...

Sam

ravon

Ashley

annie

所以我想为这个字符串创建一个数组,这样我就可以一次将第一行和第二行放入一个函数中,该函数为带有用户名和密码的 LinkedList 创建一个节点......例如用户名:Sam ,密码:拉文。然后将其加载到 LinkedList 中。当涉及到 LinkedList 时,我的所有功能都在工作,但我似乎无法将字符串拆分为数组。

我想像...

String[] userContent = content.split("\n") 会将内容的每个元素放入 userContent[n] 字符串中,其中

userContent[0] = Sam、userContent[1] = ravon 等。但是,情况并非如此。

我正在使用的代码 - 它需要一个链接列表和文件名作为参数

    public static void readUserFile(String fName, LinkedList<dataUser> ll) {
try {
File file = new File(fName);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;

while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}

LineNumberReader lnr = new LineNumberReader(new FileReader(new File("userData.txt")));
lnr.skip(Long.MAX_VALUE);
lnr.close();
fileReader.close();
int realSize = lnr.getLineNumber();
//String[] userContent = line.split("\n");
String content = stringBuffer.toString();
String[] userContent = content.split("/n");

//this prints nothing, would expect it to print exactly what content prints
for(int i = 0; i < realSize; i++) {
System.out.println(userContent[i]);
}

/* this is what I want to load the userContent string into
//not working
for(int i = 0; i < realSize; i++) {
dataUser tempUser = new dataUser(userContent[i], userContent[i+1]);
ll.add(tempUser);
i = i + 1;
}*/

//System.out.println(content); //works and prints the file with new lines
//System.out.println("Contents of file:");
//System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

对于它的值(value),以下内容将执行与您的代码所做的相同的操作,而无需创建/拆分字符串并重新打开不必要的文件,并且如果您碰巧遇到有用户但没有的文件,也不会抛出异常密码。

BufferedReader br = new BufferedReader(new FileReader(fName));
String user;

while ((user = br.readLine()) != null) {
String pass = br.readLine();
if (pass == null) {
System.out.println("Warning: User found with no password: " + user);
break;
}
ll.add(new DataUser(user, pass));
}

关于Java 将带有换行符的字符串拆分为数组,其中使用缓冲读取器从文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30359709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com