2013-11-15 70 views
0

我已經將txt文件讀入Arraylist中進行格式化,然後將該列表放入Hashset中以刪除重複項。當我嘗試寫入一個txt文件時,它將所有的值放在一行上。如果我嘗試將ArrayList寫入一個txt文件,它將分開行。任何歡迎在單獨的行上打印字符串散列集合

public static void main(String[] args) 
{ 
String filename = "data.txt"; 
String filename_out = "output.txt"; 
boolean dataRead; 
ArrayList<String> textFile = new ArrayList<String>(); 

try{ 

     Scanner datafile = new Scanner(new FileReader(filename)); 

     while(datafile.hasNext()) { 
      //Scanner readIn = new Scanner(datafile.next());//.useDelimiter("[,;:.!? ]") ; 

      textFile.add (datafile.next().replaceAll("\\p{Punct}|\\d","").toLowerCase().trim()); //reads next line, removes punctuation, sets to lowercase 

    } 

    // Collections.sort(textFile); // sort into alphabetical order 
    datafile.close(); 
    dataRead = true; 

} 
catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

ArrayList<String> dictionary = new ArrayList<String>(); 
Set<String> s = new HashSet<String>(textFile); 
for (String eachString : s) 
{ 
    dictionary.add(eachString); 
} 
Collections.sort(dictionary); 
//System.out.println(dictionary); 

try{ 
FileWriter fw = new FileWriter(filename_out); 
Writer output = new BufferedWriter(fw); 
int listSize = dictionary.size(); 
for (int i = 0; i < listSize; i++){ 
    output.write(dictionary.get(i).toString()+ "\n"); //this is where i think the problem is 
} 

output.close(); 
    } 
    catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    }   

} 
+0

我覺得這個答案應該有所幫助。 http://stackoverflow.com/a/8491808/728610 –

+1

@ArvindSridharan:當你看到一個已經回答的問題時,請將問題標記爲重複。 –

+0

哦對。我現在已經標記了它。 –

回答

0

Windows幫助使用\r\n

所以更改

output.write(dictionary.get(i).toString()+ "\n"); 

output.write(dictionary.get(i).toString()+ "\r\n"); 
+0

謝謝!這工作! –

0

使輸出的BufferedWriter和使用它的換行符()方法。

BufferedWriter output = new BufferedWriter(fw); 

... 
output.write(dictionary.get(i).toString()); 
output.newLine(); 
... 
0

試試這個

output.write(dictionary.get(i).toString()+System.getProperty("line.separator"));