我已经在一个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 :(得分:0)
Windows使用\r\n
所以改变
output.write(dictionary.get(i).toString()+ "\n");
到
output.write(dictionary.get(i).toString()+ "\r\n");
答案 1 :(得分:0)
使输出成为BufferedWriter并使用其newLine()方法。
BufferedWriter output = new BufferedWriter(fw);
...
output.write(dictionary.get(i).toString());
output.newLine();
...
答案 2 :(得分:0)
尝试这个
output.write(dictionary.get(i).toString()+System.getProperty("line.separator"));