public static void main(String[] args) {
File file = new File("num.txt");// 如果报错,可能是文件不存在
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String str = "";
List<String> list = new ArrayList<>();
while ((str = br.readLine()) != null) {
list.add(str);
}
String s1 = "", s2 = "";
List<String> same = new ArrayList<>();// 保存相同的行
int size = list.size();
while (size > 0) {
s2 = list.get(0).split(",")[0];
for (int i = 1; i < list.size(); i++) {
s1 = list.get(i).split(",")[0];// 第一个数
if (s1.equals(s2)) {
same.add(list.get(i));
}
}
if (!same.isEmpty()) {// 找到相同的
File f = new File(new Date().getTime() + ".txt");// 使用现在的时间戳作为文件名
System.out.println("创建文件...");
f.createNewFile();
same.add(list.get(0));// 把第一行加进去
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f)));
for (String ss : same) {
out.println(ss);
out.flush();
list.remove(ss);
}
out.close();
} else {
list.remove(0);
}
size = list.size();
same.clear();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
追问谢谢高手指点,还想问一下,如果要输出这些txt文件怎么办?
追答你的意思是读取这些文件的内容打印出来吗?
追问对的
追答使用BufferReqder封装InputStreamReader,然后使用readLine方法一行一行的读出来
追问能否在你之前的代码里帮忙补充一下,谢谢啦!