【发布时间】:2013-11-15 11:31:50
【问题描述】:
我已将 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();
}
}
}
【问题讨论】:
-
我认为这个答案应该会有所帮助。 stackoverflow.com/a/8491808/728610
-
@ArvindSridharan:当您看到已回答的问题时,请将问题标记为重复。
-
哦,对了。我现在已经标记了它。