package com.rscode.credits.util; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; public class FileUtil {
/**
* 根据输入流保存文件
* @param ins 输入流
* @param fileName 文件url
* @throws IOException 使用者自己处理异常
*/
public static void saveFileByInputStream(InputStream ins,String fileName) throws IOException{
FileOutputStream fos = new FileOutputStream(fileName);
byte[] b = new byte[1024];
while((ins.read(b)) != -1){
fos.write(b);
}
ins.close();
fos.close();
}
/**
* 删除文件夹下所有文件
* @param path
* @return
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete(); } }
return flag; }
/**
* 读取文本格式文件,按行读取
* @param filePath
*/
public static List<String> readTxt(String filePath) {
List<String> stringList = new ArrayList<>();
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
stringList.add(lineTxt);
}
br.close();
} else {
System.out.println("文件不存在!");
}
} catch (Exception e) {
System.out.println("文件读取错误!");
}
return stringList; }
/**
* 获取文件下所有文件
* @param path
*/
public static List<File> getFiles(String path) {
File file = new File(path);
List<File> fileList = new ArrayList<>();
// 如果这个路径是文件夹
if (file.isDirectory()) {
// 获取路径下的所有文件
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
fileList.add(files[i]);
}
}
return fileList;
}
public static void saveFileByFile(){ }
}