简体   繁体   English

从.txt文件读取arraylist

[英]Reading arraylist from a .txt file

I have an app where user inputs certain words and those words are saved to a .txt file on the device. 我有一个应用程序,用户可以输入某些单词并将这些单词保存到设备上的.txt文件中。 Then I'm creating arraylist from that .txt file. 然后,我从该.txt文件创建arraylist。 This is the code: 这是代码:

try {
        Scanner s = new Scanner(recordedFiles);
        recordedFilesArray = new ArrayList<String>();
        while (s.hasNext()){
            recordedFilesArray.add(s.next());
        }
        s.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Now, the problem is that this puts each word to arraylist, not each line. 现在的问题是,这会将每个单词而不是每一行都放到arraylist中。 So if user inputs (for example) 'test1', it'll add it to arraylist as test1 (which is fine), but if user inputs 'test 1' (with a space), 'test' and '1' will be added to arraylist as seperate elements. 因此,如果用户输入(例如)“ test1”,则会将其作为test1添加到arraylist中(很好),但是如果用户输入“ test 1”(带空格),则“ test”和“ 1”将是添加到arraylist作为单独的元素。

Showing an example how it should work: 显示一个示例它应该如何工作:

How text file looks like (example) 文本文件的外观(示例)

test 1 测试1

test 2 测试2

test 3 测试3

How arraylist looks like now: 现在arraylist的样子:

test 测试

1 1个

test 测试

2 2

test 测试

3 3

How arraylist should look like: arraylist应该是什么样的:

test 1 测试1

test 2 测试2

test 3 测试3

So my question is; 所以我的问题是; how do I add LINES to arraylist, not seperate words from a .txt file 如何将行添加到arraylist,而不是将单词与.txt文件分开

Use .nextLine() which functions as follows: 使用.nextLine() ,其功能如下:

Advances this scanner past the current line and returns the input that was skipped. 使该扫描仪前进到当前行之外,并返回被跳过的输入。 This method returns the rest of the current line, excluding any line separator at the end. 此方法返回当前行的其余部分,但不包括最后的任何行分隔符。 The position is set to the beginning of the next line. 该位置设置为下一行的开始。

As Matt Ball has indicated the while loop should use hasNextLine() instead of hasNext() 正如Matt Ball指出的那样,while循环应使用hasNextLine()而不是hasNext()

    try {
        Scanner s = new Scanner(recordedFiles);
        recordedFilesArray = new ArrayList<String>();
        while (s.hasNextLine()){
            recordedFilesArray.add(s.nextLine());
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        s.close(); //close file on success or error
    }

Documentation 文献资料

Instead of using scanner.next(); 而不是使用scanner.next(); use scanner.nextLine(); 使用scanner.nextLine();

您可以使用scanner.nextLine();

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

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