【Java】文本合并程序

来源:互联网 发布:淘宝天猫客服注意事项 编辑:程序博客网 时间:2024/05/31 19:13
先写R个文件,然后再合并到一个文件中
import java.nio.file.*;import java.util.ArrayList;import java.util.List;import java.io.*;import java.nio.charset.*;public class TxTDemo {public static void main(String[] args) {Charset chinaSet = Charset.forName("UTF-8");String directory = "F:\\file";Path path = Paths.get(directory);try {if (!Files.exists(path))//如果目录不存在,建立目录;path = Files.createDirectories(path);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//****建立R个文件***********************************int R = (int) (Math.random() * 7 + 2);System.out.println(R);List<String> fileName = new ArrayList<>(); //存储文件名for (int i = 0; i < R; i++) {//为文件命名;fileName.add(directory + "\\201411621134" + (char) ('A' + i) + ".txt");}//****向每个文件写入20个整数*****************for (String f : fileName) {String str ="";//集合整数for (int i = 0; i < 20; i++) {if (i != 0 && i % 5 == 0)//每隔五个整数换行;str += "\r\n";str += (int) (Math.random() * 101) + " ";}Path file = Paths.get(f);try (BufferedWriter buffer = Files.newBufferedWriter(file, chinaSet)) {buffer.write(str);} catch (IOException e) {e.printStackTrace();}}//****集合每个文件中大于X的整数***********int X=(int)(Math.random()*21)+20;System.out.println(X);String Str = "";//用于集合整数int count=0;//统计大于X的整数个数for(String f:fileName) {Path file=Paths.get(f);List<String> lines=null;//存储文件内容try {lines=Files.readAllLines(file,chinaSet);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(lines!=null) {for(String line:lines) {//遍历所有整数String[] num=line.split(" ");for(String s:num) {if(Integer.parseInt(s)>X) {Str+=(s+" ");count++;if(count%10==0)//每插入10个整数就插入一个换行符;Str+="\r\n";}}}}}//****把大于X的整数写入文件中***********************Path files = Paths.get(directory + "\\201411621134.txt");try(BufferedWriter buffer=Files.newBufferedWriter(files, chinaSet)){buffer.write(Str.trim());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(count);List<String> linesRead=null;try {linesRead=Files.readAllLines(files,chinaSet);}catch(IOException e) {e.printStackTrace();}if(linesRead!=null) {for(String lines:linesRead) {System.out.println(lines);//在屏幕显示文件的内容;}}}}

原创粉丝点击