import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
/**
* TODO
*
* @Author seems
* @Date 2021/5/28 下午 09:07
*/
public class FileUntils {
// 高效读取txt文本
public static String getTxtContent(File file, Charset charset) throws IOException {
Path path = file.toPath();
// 一个文本文件如果已经大于int最大值,这种文件一般来说很少见有可能是log文件
if (file.length() <= Integer.MAX_VALUE - 8) {
// 使用nio提高读取速度
try (FileChannel in = FileChannel.open(path, StandardOpenOption.READ)) {
ByteBuffer byteBuffer = ByteBuffer.allocate((int) in.size());
in.read(byteBuffer);
in.close();
System.out.println(byteBuffer);
System.out.println(byteBuffer.array());
return new String(byteBuffer.array(), charset);
}
}
StringBuilder msg = new StringBuilder();
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
for (; ; ) {
String line = reader.readLine();
if (line == null) {
break;
}
msg.append(line);
}
}
return msg.toString();
}
public static String getTxtContent(File file) throws IOException {
FileReader fr = null;
BufferedReader br = null;
StringBuffer txt = new StringBuffer();
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
txt.append(line);
txt.append("\n");
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return txt.toString();
}
// 读取文件名
public static void getFileName(String path){
// get file list where the path has
File file = new File(path);
// get the folder list
File[] array = file.listFiles();
for(int i=0;i<array.length;i++){
if(array[i].isFile()){
System.out.println(array[i].getName());
System.out.println(array[i]);
System.out.println(array[i].getPath());
}else if(array[i].isDirectory()){
getFileName(array[i].getPath());
}
}
}
}
版权归属:
seems
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区