指定目录中查找文件
public static List<String> findFile(File target,String fileName){
ArrayList<String> path = new ArrayList<>();
if(target==null) {
return path;
}
if(target.isDirectory()){
File[] files = target.listFiles();
if(files!=null){
for(File f: files){
findFile(f,fileName);
}
}
}else{
String name = target.getName().toLowerCase();
if(name.contains(fileName)){
path.add(target.getAbsolutePath());
}
}
return path;
}
文件合并分割
/**
* 文件分割
* @param targetFile 待分割文件
* @param cutSize 每个文件大小
*/
public static void division(File targetFile, long cutSize,String targetPath) {
if (targetFile == null) {
return;
}
// 计算总分割的文件数
int num = targetFile.length() % cutSize == 0 ? (int) (targetFile.length() / cutSize):(int) (targetFile.length() / cutSize + 1);
try {
// 构造一个文件输入流
BufferedInputStream in = new BufferedInputStream(new FileInputStream(targetFile));
BufferedOutputStream out = null;
byte[] bytes = null;
int len = -1;
int count = 0;
//循环次为生成文件的个数
for (int i = 0; i < num; i++) {
out = new BufferedOutputStream(
new FileOutputStream(new File(targetPath+ (i + 1) + "-temp-" + targetFile.getName())));
if (cutSize <= 1024) {
bytes = new byte[(int) cutSize];
count = 1;
} else {
bytes = new byte[1024];
count = (int) cutSize / 1024;
}
//count放在前面避免多度一次
while (count > 0 && (len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
count--;
}
//计算每个文件大小除于1024的余数,决定是否要再读取一次
if (cutSize % 1024 != 0) {
bytes = new byte[(int) cutSize % 1024];
len = in.read(bytes);
out.write(bytes, 0, len);
out.flush();
out.close();
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 合并文件
* @param es 待合并的文件
* @param targetFile 目标文件
*/
public static void merge(Enumeration<InputStream> es, String targetFile) {
SequenceInputStream sis = new SequenceInputStream(es);
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(targetFile));
byte[] bytes = new byte[1024];
int len = -1;
while((len=sis.read(bytes))!=-1){
bos.write(bytes,0,len);
bos.flush();
}
bos.close();
sis.close();
System.out.println("合并完成.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
标签:JAVA,bytes,查找文件,targetFile,len,IO,new,cutSize,out
From: https://blog.csdn.net/qq_26594041/article/details/142307687