繁体   English   中英

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

[英]Java splitting a string with newlines into an array, where the string is read from a file using buffered reader

我正在将文件加载到缓冲区中,该缓冲区也加载到字符串缓冲区中。 然后,我将该字符串缓冲区复制到字符串中。 字符串显示为...

山姆

RAVON

阿什利

安妮

因此,我想为此字符串创建一个数组,以便可以一次将第一行和第二行放入一个函数中,该函数为使用用户名和密码的LinkedList创建一个节点... ex用户名:Sam,密码:ravon 。 然后将其加载到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();
    }
}

值得这样做的是,以下代码将执行您的代码所做的相同操作,而无需创建/拆分字符串并不必要地重新打开文件,并且如果您碰巧使用用户但没有密码运行到文件中,也不会引发异常。

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));
}

现在您只检查空白,

split("\n")

使用%% n作为新行,或者可以使用不是字母数字字符的%% W进行编码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM