标签:NPU ati ret import reader rect 解决 names puts
package com.test.springboot.util;
import java.io.*;
/**
* 按行分割文件 工具类
*
* @author FX_SKY
*/
public class FileSplitUtil {
/**
* @param args
*/
public static void main(String[] args) {
splitDataToSaveFile(9,
"E:\\123\\uploadFile.html",
"D:\\java\\cuts",
"UTF-8");
}
/**
* 按行分割文件
*
* @param rows 为多少行一个文件
* @param sourceFilePath 为源文件路径
* @param targetDirectoryPath 文件分割后存放的目标目录
* @param coding 编码格式 解决中文乱码
*/
public static void splitDataToSaveFile(int rows, String sourceFilePath,
String targetDirectoryPath, String coding) {
// String coding="UTF-8";//UTF-8//GBK
System.out.println("文件分割开始.....");
File sourceFile = new File(sourceFilePath);//源文件
File targetFile = new File(targetDirectoryPath);//目标文件夹
if (!sourceFile.exists() || rows <= 0 || sourceFile.isDirectory()) {//源文件是否存在
System.out.println("文件不存在");
return;
}
if (targetFile.exists()) {
if (!targetFile.isDirectory()) {//判断目标是否是一个目标文件夹
System.out.println("目标文件不是文件夹");
return;
}
} else {
targetFile.mkdirs();//不存在创建
}
try {
InputStreamReader in = new InputStreamReader(new FileInputStream(sourceFilePath), coding);
BufferedReader br = new BufferedReader(in);
BufferedWriter bw = null;
String str = "";
String tempData = br.readLine();//读取行
int i = 1, s = 0;
while (tempData != null) {//行若不为空
str += tempData + "\r\n";
if (i % rows == 0) {//取余行数 符合所设定的行数 则一起输出,否则继续读
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
targetFile.getAbsolutePath() + "/" + (s + 1) + getExtension(sourceFilePath)), coding), 1024);
bw.write(str);
bw.close();
str = "";
s += 1;
}
i++;
tempData = br.readLine();
}
int t = 0;
if ((i - 1) % rows != 0) {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
targetFile.getAbsolutePath() + "/" + (s + 1) + getExtension(sourceFilePath)), coding), 1024);
bw.write(str);
bw.close();
br.close();
t = s;
s += 1;
System.out.println("最后一个文件输出完成!!");
}
in.close();
int y = i-1;
int z = 0;
int x=y%rows;
if (x== 0) {
z = y/rows;
}else {
z = y/rows+1;
System.out.println("最后一个文件行数:"+x);
}
System.out.println("文件分割完成!!");
System.out.println(" "+"文件总行数= " + y);
System.out.println(" "+rows + "行一个文件");
System.out.println(" "+"结果分成文件个数= " + z);
} catch (Exception e) {
}
}
//获取后缀名
public static String getExtension(String filename) {
String nameSuffix = filename.substring(filename.lastIndexOf("."));
return nameSuffix;
}
}
标签:NPU ati ret import reader rect 解决 names puts
原文地址:https://www.cnblogs.com/ynhk/p/10897814.html