@ApiOperation("批量下载并打成压缩包zip格式")
@Log(title = "批量下载并打成压缩包zip格式", businessType = BusinessType.OTHER)
@PostMapping("/common/downloadZipFiles")
@ResponseBody
public void downloadFiles(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject jsonParam) throws Exception {
ArrayList<Object> pathArray=(ArrayList)jsonParam.get("remoteDirectoryPath");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = "myData_" + sdf.format(new Date());
String utf = "UTF-8";
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition",
"attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fn+".zip"));
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);
} catch (Exception e) {
e.printStackTrace();
}
String filePath = geneConfig.getFileUploadPath()+fn;
for (Object pathObj:pathArray){
HashMap jsonObject=(HashMap)pathObj;
Integer type=(Integer)jsonObject.get("type");
String path=(String)jsonObject.get("path");
if (0==type){
File file = new File(path);
CreateFileUtil.copyFolder(path,filePath+File.separator+file.getName());
}else {
File file = new File(path);
CreateFileUtil.copyFile(path,filePath+File.separator+file.getName());
}
}
File sourceFile = new File(filePath);
ZipUtils.compress(sourceFile,zipos,sourceFile.getName(),true);
try {
zipos.closeEntry();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
package com.hessianhealth.common.utils.file;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class FileUtils extends org.apache.commons.io.FileUtils
{
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
if (os != null)
{
try
{
os.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fis != null)
{
try
{
fis.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
public static boolean deleteFile(String filePath)
{
boolean flag = false;
File file = new File(filePath);
if (file.isFile() && file.exists())
{
file.delete();
flag = true;
}
return flag;
}
public static boolean isValidFilename(String filename)
{
return filename.matches(FILENAME_PATTERN);
}
public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
throws UnsupportedEncodingException
{
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE"))
{
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
}
else if (agent.contains("Firefox"))
{
filename = new String(fileName.getBytes(), "ISO8859-1");
}
else if (agent.contains("Chrome"))
{
filename = URLEncoder.encode(filename, "UTF-8");
}
else
{
filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
return filename;
}
public static String convertEncodingFormat(String str, String formatFrom, String FormatTo) {
String result = null;
if (!(str == null || str.length() == 0)) {
try {
result = new String(str.getBytes(formatFrom), FormatTo);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result;
}
public static String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}
public static ArrayList<Object> getAllFile(String path) {
ArrayList<Object> list = new ArrayList();
File file = new File(path);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File file1 = files[i];
String fileName = file1.getName();
list.add(fileName);
}
return list;
}
public static Object readJsonFile(File jsonFile) {
String jsonStr = "";
try {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
return jsonObject;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void writeJsonFileByString(String newJsonString, String path){
try {
FileWriter fw = new FileWriter(path);
PrintWriter out = new PrintWriter(fw);
out.write(newJsonString);
out.println();
fw.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void DirAll(List<String> dirAllStrArr, File dirFile,Map map) throws Exception {
if (dirFile.exists()) {
File files[] = dirFile.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("-------文件夹-----"+file.getName());
DirAll(dirAllStrArr, file,map);
} else {
if (dirFile.getPath().endsWith(File.separator)) {
System.out.println("------2------"+file.getName());
dirAllStrArr.add(dirFile.getPath()+ File.separator + file.getName());
} else {
System.out.println("------文件-----"+file.getName());
dirAllStrArr.add(dirFile.getPath() + File.separator
+ file.getName());
map.put(file.getName(),file.getName());
}
}
}
}
}
private static void getFilePath(String filePath) {
File file = new File(filePath);
if (file.isDirectory()){
System.out.println("---------------:"+filePath);
File[] listFiles = file.listFiles();
for (int i = 0 ;i<listFiles.length;i++){
getFilePath(listFiles[i].getAbsolutePath());
}
}
}
public static void isDirectory(File file) {
if(file.exists()){
if (file.isFile()) {
System.out.println("file is ==>>" + file.getAbsolutePath());
}else{
File[] list = file.listFiles();
if (list.length == 0) {
System.out.println(file.getAbsolutePath() + " is null");
} else {
for (int i = 0; i < list.length; i++) {
isDirectory(list[i]);
}
}
}
}else{
System.out.println("文件不存在!");
}
}
private static void getFile(String path,int deep){
File file = new File(path);
File[] array = file.listFiles();
for(int i=0;i<array.length;i++)
{
if(array[i].isFile())
{
for (int j = 0; j < deep; j++)
System.out.print(" ");
System.out.println("1:"+ array[i].getName()+" 文件大小:"+array[i].length());
}
else if(array[i].isDirectory())
{
for (int j = 0; j < deep; j++)
System.out.print(" ");
System.out.println("2:"+ array[i].getName()+" 文件大小:"+array[i].length());
getFile(array[i].getPath(),deep+1);
}
}
}
public static JSONArray getDirectoryFilesPath(String path) {
File dirFile = new File(path);
Map<String, JSONArray> map = new HashMap<>();
if (dirFile.exists()) {
File files[] = dirFile.listFiles();
for (File file : files) {
String createTime = getFileTime(file, "createTime");
String lastmodfiyTime = getFileTime(file, "lastmodfiyTime");
if (file.isDirectory()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type",0);
jsonObject.put("fileName",file.getName());
jsonObject.put("length", "");
jsonObject.put("createTime",createTime);
jsonObject.put("lastmodfiyTime",lastmodfiyTime);
jsonObject.put("path",dirFile.getPath()+ File.separator + file.getName());
if (map.containsKey(createTime)) {
JSONArray array = map.get(createTime);
array.add(jsonObject);
} else {
JSONArray array = new JSONArray();
array.add(jsonObject);
map.put(createTime,array);
}
} else {
if (dirFile.getPath().endsWith(File.separator)) {
} else {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type",1);
jsonObject.put("fileName",file.getName());
jsonObject.put("length",FileUtils.getPrintSize(file.length()));
jsonObject.put("createTime",createTime);
jsonObject.put("lastmodfiyTime", lastmodfiyTime);
jsonObject.put("path",dirFile.getPath() + File.separator
+ file.getName());
if (map.containsKey(createTime)) {
JSONArray array = map.get(createTime);
array.add(jsonObject);
} else {
JSONArray array = new JSONArray();
array.add(jsonObject);
map.put(createTime,array);
}
}
}
}
}
JSONArray dirAllStrArr = new JSONArray();
Object[] key_arr = map.keySet().toArray();
Arrays.sort(key_arr);
for (Object key : key_arr) {
JSONArray value = map.get(key);
dirAllStrArr.addAll(value);
}
return dirAllStrArr;
}
public static long getFileSize3(File file){
FileChannel fc = null;
long size=0;
try{
if(file.exists() &&file.isFile()){
String fileName =file.getName();
FileInputStream fis = new FileInputStream(file);
fc =fis.getChannel();
size=fc.size();
System.out.println("文件"+fileName+"的大小是:"+fc.size()+"\n");
}
} catch(Exception e) {
e.printStackTrace();
}finally{
if(null!=fc){
try{
fc.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
return size;
}
public static String getFileTime(File file,String type) {
if (file == null) {
return null;
}
BasicFileAttributes attr = null;
try {
Path path = file.toPath();
attr = Files.readAttributes(path, BasicFileAttributes.class);
} catch (IOException e) {
e.printStackTrace();
}
Instant instant;
if ("createTime".equals(type)){
instant = attr.creationTime().toInstant();
}else{
instant = attr.lastModifiedTime().toInstant();
}
String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(instant);
return format;
}
public static String getPrintSize(long size) {
if (size < 1024) {
return String.valueOf(size) + "B";
} else {
size = size / 1024;
}
if (size < 1024) {
return String.valueOf(size) + "KB";
} else {
size = size / 1024;
}
if (size < 1024) {
size = size * 100;
return String.valueOf((size / 100)) + "."
+ String.valueOf((size % 100)) + "MB";
} else {
size = size * 100 / 1024;
return String.valueOf((size / 100)) + "."
+ String.valueOf((size % 100)) + "GB";
}
}
public static MultipartFile getMulFileByFile(File file) {
FileItem fileItem = createFileItem(file.getPath(),file.getName());
MultipartFile mfile = new CommonsMultipartFile(fileItem);
return mfile;
}
public static FileItem createFileItem(String filePath,String fileName){
String fieldName = "file";
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
File newfile = new File(filePath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try
{
FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
{
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return item;
}
public static void copyFileUsingFileStreams(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf))!= -1) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
public static void writeJsonFile(String newJsonString, String path){
try {
FileWriter fw = new FileWriter(path);
PrintWriter out = new PrintWriter(fw);
out.write(newJsonString);
out.println();
fw.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<String> readFile02(String path) throws IOException {
List<String> list = new ArrayList<String>();
FileInputStream fis = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null) {
if (line.lastIndexOf("---") < 0) {
list.add(line);
}
}
br.close();
isr.close();
fis.close();
return list;
}
public MultipartFile fileToMultipartFile(File file) {
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
private static FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
public static void main(String[] args) throws Exception {
}
}
package com.hessianhealth.common.utils.file;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
zos.putNextEntry(new ZipEntry(name));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
if(KeepDirStructure){
zos.putNextEntry(new ZipEntry(name + "/"));
zos.closeEntry();
}
}else {
for (File file : listFiles) {
if (KeepDirStructure) {
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}
public static void main(String[] args) throws Exception {
FileOutputStream fos1= new FileOutputStream(new File("E:/testZip.zip"));
ZipUtils.toZip("E:/testZip", fos1,true);
List<File> fileList = new ArrayList<>();
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
FileOutputStream fos2= new FileOutputStream(new File("c:/mytest02.zip"));
ZipUtils.toZip(fileList, fos2);
}
}
package com.hessianhealth.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.hessianhealth.common.config.geneConfig;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class CreateFileUtil {
public static String getfilePath(){
String filePath = getSaveFilePath(null);
String fileName = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String date=df.format(new Date());
fileName=filePath+date+"-"+"脑梗死KPI.xlsx";
return fileName;
}
public static String getSaveFilePath(String fileType) {
String filePath = null;
String property = System.getProperty("os.name").toLowerCase();
System.out.println("系统名称:"+property);
int indexOf = property.indexOf("windows");
if (indexOf == 0) {
String userHome = System.getProperty("user.home");
filePath = userHome + "\\Desktop\\downFile\\";
createParentFile(filePath);
} else {
switch(fileType){
case "image":
filePath= geneConfig.getImageUrl();
break;
default:
filePath= geneConfig.getUploadPath();
break;
}
System.out.println("路径名称:"+filePath);
createParentFile(filePath);
}
return filePath;
}
public static void createParentFile(String filePath) {
File file = new File(filePath);
boolean exists = file.exists();
if (exists) {
boolean directory = file.isDirectory();
if (directory) {
file.mkdir();
}
} else {
file.mkdir();
}
}
public static Boolean delFile(String filePath){
File file = new File(filePath);
if (file.exists()) {
return file.delete();
}
return null;
}
public static ResponseEntity<byte[]> downLoadFile(String fileName, byte[] fileData) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
return new ResponseEntity<>(fileData,headers, HttpStatus.CREATED);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static ResponseEntity<byte[]> downLoadFile(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("-------downLoadFile---------"+"文件不存在");
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {
headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
boolean flag = true;
String fullPath = filePath + File.separator + fileName + ".json";
try {
File file = new File(fullPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
file.createNewFile();
jsonString = JsonFormatTool.formatJson(jsonString);
Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
write.write(jsonString);
write.flush();
write.close();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
public static void createTxtFile(List<Map<String, String>> contentList, String filePath, String fileName) throws IOException {
String fullPath1 = filePath + File.separator + fileName + "_temp.txt";
String fullPath = filePath + File.separator + fileName + ".txt";
File filenameShip = new File(fullPath1);
if (!filenameShip.getParentFile().exists()) {
filenameShip.getParentFile().mkdirs();
}
if (filenameShip.exists()) {
filenameShip.delete();
}
String readStr = "\t";
FileWriter writer = null;
for (int i = 0; i < contentList.size(); i++) {
HashMap<String, String> map=(HashMap<String, String>) contentList.get(i);
String filein1 = "\r\n" ;
for (int j = 0; j < map.size()-1; j++) {
filein1+=map.get((1+j)+"")+ readStr;
}
filein1+=map.get((map.size())+"");
filein1+="\r\n";
try {
writer = new FileWriter(filenameShip, true);
writer.write(filein1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
readLocalFile(fullPath1,fullPath,contentList.size());
}
public static void readLocalFile(String fullPath1, String fullPath, int size){
String filename1=fullPath1;
String filename2=fullPath;
File file=new File(filename1);
InputStream is=null;
BufferedReader br = null;
String tmp;
FileWriter writer=null;
int i=0;
try {
is=new BufferedInputStream(new FileInputStream(file));
br = new BufferedReader(new InputStreamReader(is, "utf-8"));
writer = new FileWriter(filename2, true);
while((tmp=br.readLine())!=null){
if(tmp.equals(""));
else{
if (i ==(size-1)){
writer.write(tmp);
}else {
writer.write(tmp+"\n");
i++;
}
}
}
writer.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
File filenameShip = new File(fullPath1);
filenameShip.delete();
}
public static void readLocalFile111(String[] args){
String line=null;
int i=0;
File file=new File(args[0]);
File file1=new File(args[1]);
if(args[0].endsWith("txt")&args[1].endsWith("txt"))
{
if(!file.exists())
{
System.out.println("文件不存在!");
System.exit(0);
}
try
{
Runtime.getRuntime().exec("notepad "+args[0]);
InputStreamReader Stream=new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader reader=new BufferedReader(Stream);
OutputStreamWriter outStream=new OutputStreamWriter(new FileOutputStream(file1),"UTF-8");
BufferedWriter writer=new BufferedWriter(outStream);
while((line=reader.readLine())!=null)
{
if(line.equals(""))
{
continue;
}
else
{
i++;
writer.write("["+i+"]");
writer.write(line+"\r\n");
}
}
writer.close();
reader.close();
System.out.println("修改完成!");
}
catch(Exception e)
{
e.printStackTrace();
}
try{
Runtime.getRuntime().exec("notepad "+args[1]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("输入错误!(非.txt)");
System.exit(0);
}
}
public static String ReadFile(String path){
String laststr="";
File file=new File(path);
BufferedReader reader=null;
try{
FileInputStream in = new FileInputStream(file);
reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
String tempString=null;
while((tempString=reader.readLine())!=null){
laststr=laststr+tempString;
}
reader.close();
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOException el){
}
}
}
return laststr;
}
public static List<JSONObject> readfile(String filepath) throws FileNotFoundException, IOException {
List<JSONObject> list= new ArrayList();
try {
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("文件");
System.out.println("path=" + file.getPath());
System.out.println("absolutepath=" + file.getAbsolutePath());
System.out.println("name=" + file.getName());
} else if (file.isDirectory()) {
System.out.println("文件夹");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("path=" + readfile.getPath()+"========="+readfile.getName());
JSONObject jsonObject = new JSONObject();
jsonObject.put("path",readfile.getPath());
jsonObject.put("name",readfile.getName());
list.add(jsonObject);
} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return list;
}
public static void qukonghang () {
String filename1="C:\\home\\data\\config\\20210908163757\\20210908163757_rename.txt";
String filename2="C:\\home\\data\\config\\20210908163757\\20210908163757_rename1234.txt";
File file=new File(filename1);
InputStream is=null;
BufferedReader br = null;
String tmp;
FileWriter writer=null;
int i=0;
try {
is=new BufferedInputStream(new FileInputStream(file));
br = new BufferedReader(new InputStreamReader(is, "utf-8"));
writer = new FileWriter(filename2, true);
while((tmp=br.readLine())!=null){
System.out.println(i+"-----:"+tmp.trim());
if(tmp.trim().equals(""));
else{
if (i ==2){
writer.write(tmp);
}else {
writer.write(tmp+"\n");
i++;
}
}
}
writer.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readLastLine(File file, String charset) throws IOException {
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return null;
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "r");
long len = raf.length();
if (len == 0L) {
return "";
} else {
long pos = len - 1;
while (pos > 0) {
pos--;
raf.seek(pos);
if (raf.readByte() == '\n') {
break;
}
}
if (pos == 0) {
raf.seek(0);
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
if (charset == null) {
return new String(bytes);
} else {
return new String(bytes, charset);
}
}
} catch (FileNotFoundException e) {
} finally {
if (raf != null) {
try {
raf.close();
} catch (Exception e2) {
}
}
}
return null;
}
public static void createNewFile( String filePath)throws IOException {
File checkFile = new File(filePath);
try {
if (!checkFile.getParentFile().exists()) {
checkFile.getParentFile().mkdirs();
}
if (!checkFile.exists()) {
checkFile.createNewFile();
}else {
checkFile.delete();
checkFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) {
File file = new File(newPath);
if (!file.exists()){
createNewFile(newPath);
}
InputStream inStream = new FileInputStream(oldPath);
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
public static void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs();
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}
else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
qukonghang();
} catch (Exception e) {
e.printStackTrace();
}
}
}