Split text file into Strings on empty line

后端 未结 6 1590
温柔的废话
温柔的废话 2021-02-15 16:12

I want to read a local txt file and read the text in this file. After that i want to split this whole text into Strings like in the example below .

Example : Lets say

6条回答
  •  萌比男神i
    2021-02-15 16:30

    @Kevin code works fine and as he mentioned that the code was not tested, here are the 3 changes required:

    1.The if check for (tmp==null) should come first, otherwise there will be a null pointer exception.

    2.This code leaves out the last set of lines being added to the ArrayList. To make sure the last one gets added, we have to include this code after the while loop: if(!str.isEmpty()) { allStrings.add(str); }

    3.The line str += "\n" + tmp; should be changed to use \n instead if \\n. Please see the end of this thread, I have added the entire code so that it can help

    BufferedReader in
       = new BufferedReader(new FileReader("foo.txt"));
    
    List allStrings = new ArrayList();
    String str ="";
    List allStrings = new ArrayList();
            String str ="";
            while(true)
            {
                String tmp = in.readLine();
                if(tmp==null)
                {
                    break;
                }else if(tmp.isEmpty())
                {
                    if(!str.isEmpty())
                    {
                        allStrings.add(str);
                    }
                    str= "";
                }else
                {
                    if(str.isEmpty())
                    {
                        str = tmp;
                    }
                    else
                    {
                        str += "\n" + tmp;
                    }
                }
    
            }
            if(!str.isEmpty())
            {
                allStrings.add(str);
            }
    

提交回复
热议问题