按行写入文件内容如下:import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.TreeSet;public class writeFile { public void fileWriter(String fileName,TreeSetclist) throws IOException{ //创建一个FileWriter对象 FileWriter fw = new FileWriter(fileName); //遍历clist集合写入到fileName中 for (String str: clist){ fw.write(str); fw.write("\n"); } //刷新缓冲区 fw.flush(); //关闭文件流对象 fw.close(); } public TreeSet readFileByLines(String fileName) throws IOException{ File file = new File(fileName); BufferedReader reader = new BufferedReader(new FileReader(file)); String tempString = null; //创建一个集合 TreeSet nums = new TreeSet (); //按行读取文件内容,并存放到集合 while ((tempString = reader.readLine()) != null){ nums.add(tempString); } reader.close(); //返回集合变量 return nums; } public static void main(String[] args) throws IOException{ //创建writeFile对象wf writeFile wf = new writeFile(); //读取文件内容保存到一个集合对象中 TreeSet ts = wf.readFileByLines("F:/A_remain.txt"); //将集合对象ts的内容保存到text.txt文件中 wf.fileWriter("F:/text.txt", ts); }}
A_remain.txt文件内容如下:
BGP-HK-1-3TQCCN-BJ-7-351CCN-BJ-7-353CCN-BJ-7-356CCN-BJ-7-358CCN-BJ-H-381CCN-BJ-H-382CCN-BJ-H-3F1CER-BJ-3-33CCER-BJ-3-355CER-BJ-3-356CER-BJ-3-357
执行程序后,text.txt文件的内容如下:BGP-HK-1-3TQCCN-BJ-7-351CCN-BJ-7-353CCN-BJ-7-356CCN-BJ-7-358CCN-BJ-H-381CCN-BJ-H-382CCN-BJ-H-3F1CER-BJ-3-33CCER-BJ-3-355CER-BJ-3-356CER-BJ-3-357