简体   繁体   中英

trying to read from a file and split it into words and store those words in an arrayList

in my code when i want to print out the list , there is return of line and i don't know how to get rid of it, for example if my file contain those lines:
i can't think of anything to write
blah blah blah
when i print out my list i got this:
{i, can't, think, of, anything, to, write
blah,blah , blah}

this is my code:

    public static void main(String[] args) {

    ArrayList<String> list = new ArrayList<>() ;   
    try(BufferedReader br = new BufferedReader(new FileReader("test.txt"));){

        int i = 0;

        String str = " ";
        while((i = br.read()) != -1){

            str += (char) i;

            if( (char) i == ' '){

               list.add(str.toString());
               str = " " ;
           }

        }
        list.add(str.toString());

       }catch (Exception e){
           System.out.println("there is an exception ");
       }
    printArrayList(list);
}

public static void printArrayList(ArrayList<String> list){
    System.out.print("{");
    for(int i = 0; i<list.size(); i++){

        if (i > 0)
        System.out.print("," + list.get(i));
        else 
            System.out.print(list.get(i));
    }
    System.out.print("}");


}

Are you opposed to importing a library? Apache StringUtils has a method that splits on whitespace, returning everything else in tokens.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#split%28java.lang.String%29

This is happening because you are only splitting the sentence when you find a space if( (char) i == ' ') . If you want to split it on new lines also, use

if ( (char) i == ' ' || (char) i == '\\n')

Note: \\n is not the line separating character in all the platforms. AFAIK, it can be anyone of \\n or \\r or \\r\\n ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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