2015-06-28 78 views
0

在我的代码中,当我要打印出列表时,存在行的返回并且我不知道如何摆脱它,例如,如果我的文件包含这些行:
我想不出有什么可写
等等等等
当我打印出我的列表我得到这个:
{我,不能,想到的,任何能,写
胡说,胡说,胡说}试图从文件中读取并将其拆分为单词并将这些单词存储在arrayList中

这是我的代码:

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


} 
+0

你需要什么格式? –

+0

我想得到如下列表:{我,不能,想,什么,写,等等,等等,等等}没有返回线! –

+0

只是改变到=>如果(** ** list.get(ⅰ)。载( “\ n”)){ \t \t \t \t \t是System.out.print( “” + list.get(ⅰ )); \t \t \t \t} ........... if case has“!”即。不包含“\ n”新行 –

回答

0

发生这种情况是因为只有在找到空格if((char) i == ' ')时才会分割句子。如果你想它也被分成上新的生产线,使用

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

注:\n是不是在所有的平台分隔符行。 AFAIK,它可以是任何人\n\r\r\n ..

+0

我试过这个,但我得到了同样的结果! –

+0

你也试过使用'\ r'吗?正如我所说,'\ n'不是所有平台上的行分隔符... – Codebender

+0

是的,我试过\ r它不工作,即时通过使用eclipse的方式 –

相关问题