先写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 block
e.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 block
e.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 block
e.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);//在屏幕显示文件的内容;
}
}
}
}