目录
1、创建文件夹
package utill;
import java.io.File;
public class fileUtill {
public static void main(String[] args) {
String filepPath="D:/file/flie";
File myFolderPath = new File(filepPath);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
System.out.println("新建目录操作成功!");
}
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
}
2、创建文件
package utill;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class fileUtill {
public static void main(String[] args) {
String filepPath="D:/file/flie.txt";
File myFilePath = new File(filepPath);
try {
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
resultFile.close();
System.out.println("新建文件操作成功!");
}
catch (Exception e) {
System.out.println("新建文件操作出错!");
e.printStackTrace();
}
}
}
3、删除指定文件
package utill;
import java.io.File;
public class fileUtill {
public static void main(String[] args) {
String filepPath="D:/file/flie.txt";
File myFilePath = new File(filepPath);
try {
myFilePath.delete();
System.out.println("删除文件成功!");
}
catch (Exception e) {
System.out.println("删除文件失败!");
e.printStackTrace();
}
}
}
4、删除指定文件夹
package utill;
import java.io.File;
public class fileUtill {
public static void main(String[] args) {
String filepPath="D:/file/flie";
File myFilePath = new File(filepPath);
try {
//删除空文件夹
myFilePath.delete();
System.out.println("删除文件夹成功!");
}
catch (Exception e) {
System.out.println("删除文件夹失败!");
e.printStackTrace();
}
}
}
5、删除某个文件夹下所有的文件夹
package utill;
import java.io.File;
public class fileUtill {
public static void main(String[] args) {
String filepPath="D:/file/flie";
File myFilePath = new File(filepPath);
try {
File[] files=myFilePath.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
files[i].delete();
}
}
System.out.println("删除文件夹成功!");
}
catch (Exception e) {
System.out.println("删除文件夹失败!");
e.printStackTrace();
}
}
}
6、清空文件夹(包含文件及文件夹)
package utill;
import java.io.File;
public class fileUtill {
//用来判断文件是否删除成功
static int flag = 1;
public static void main(String[] args) {
//要删除文件目录的绝对路径
String filepPath="D:/file/flie";
File myFilePath = new File(filepPath);
//删除一个文件夹下的所有文件(包括子目录内的文件)
deleteFile(myFilePath);
if (flag == 1){
System.out.println("文件删除成功!");
}
}
public static void deleteFile(File file){
//判断文件不为null或文件目录存在
if (file == null || !file.exists()){
flag = 0;
System.out.println("文件删除失败,请检查文件路径是否正确");
return;
}
//取得这个目录下的所有子文件对象
File[] files = file.listFiles();
//遍历该目录下的文件对象
for (File f: files){
//打印文件名
String name = file.getName();
System.out.println(name);
//判断子目录是否存在子目录,如果是文件则删除
if (f.isDirectory()){
deleteFile(f);
}else {
f.delete();
}
}
//删除空文件夹 for循环已经把上一层节点的目录清空。
file.delete();
}
}
7、读取文件
package utill;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class fileUtill {
public static void main(String[] args) {
//要读取文件目录的绝对路径
String filepPath="D:/file/flie.txt";
readFileByBytes(filepPath);
readFileByChars(filepPath);
readFileByLines(filepPath);
readFileByRandomAccess(filepPath);
testReadFile(filepPath);
testReadFile11(filepPath);
}
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读取一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
System.out.println("--------------------------------------------------------------------------------------------");
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读取多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读取一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try (Scanner sc = new Scanner(new FileReader(fileName))) {
while (sc.hasNextLine()) { //按行读取字符串
String line = sc.nextLine();
System.out.println("按行读取字符串:"+line);
}
} catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try (Scanner sc = new Scanner(new FileReader(fileName))) {
sc.useDelimiter("\\|"); //按分隔符
while (sc.hasNext()) { //按分隔符读取字符串
String str = sc.next();
System.out.println("按分隔符:"+str);
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//sc.hasNextInt() 、hasNextFloat() 、基础数据类型等等等等。
//文件内容:1|2
try (Scanner sc = new Scanner(new FileReader(fileName))) {
sc.useDelimiter("\\|"); //按"|"分隔符
while (sc.hasNextInt()) { //按分隔符读取Int
int intValue = sc.nextInt();
System.out.println("按\"|\"分隔符:"+intValue);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
//jdk8
public static void testReadFile(String fileName) {
File file = new File(fileName);
Stream<String> lines=null;
try {
// 读取文件内容到Stream流中,按行读取
lines = Files.lines(Paths.get(fileName));
// 1、随机行顺序进行数据处理(forEach获取Stream流中的行数据不能保证顺序,但速度快。如果你想按顺序去处理文件中的行数据,可以使用forEachOrdered,但处理效率会下降。)
lines.forEach(ele -> {
System.out.println("读取文件内容到Stream流中,按行读取:"+ele);
});
// 2、或按文件行顺序进行处理(使用forEachOrdered,处理效率会下降)
lines.forEachOrdered(System.out::println);
// 3、或按文件行顺序进行处理(利用CPU多和的能力,进行数据的并行处理parallel(),适合比较大的文件)
lines.parallel().forEachOrdered(System.out::println);
//4、也可以把Stream<String>转换成List<String>,但是要注意这意味着你要将所有的数据一次性加载到内存,要注意java.lang.OutOfMemoryError: Java heap space
List<String> collect = lines.collect(Collectors.toList());
for(String list : collect) {
System.out.println(list);
}
// 5、如果我们不需要Stream<String>,我们想直接按行读取文件获取到一个List<String>, 要注意java.lang.OutOfMemoryError: Java heap space
List<String> linestr = Files.readAllLines(Paths.get(fileName),
StandardCharsets.UTF_8);
linestr.forEach(System.out::println);
lines.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (lines != null) {
lines.close();
}
}
}
//jdk11
public static void testReadFile11(String fileName) {
// java 11 开始提供的方法,读取文件不能超过2G,与你的内存息息相关
String str = Files.readString(Paths.get(fileName));
System.out.println(str);
//如果是JDK11用上面的方法,如果不是用这个方法也很容易
byte[] bytes = Files.readAllBytes(Paths.get(fileName));
String content = new String(bytes, StandardCharsets.UTF_8);
System.out.println(content);
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
}
8、写入文件
package utill;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
public class fileUtill {
public static void main(String[] args) {
//要写入文件目录的绝对路径
String filepPath="D:/file/flie.txt";
writeFileWriter(filepPath);
writeBufferedWriter(filepPath);
writeFileWriter2(filepPath);
appendRandomAccessFile(filepPath, "123");
}
/**
* 使用FileWriter类写文本文件
*/
public static void writeFileWriter(String fileName)
{
try
{
//使用这个构造函数时,如果存在kuka.txt文件,
//则先把这个文件给删除掉,然后创建新的kuka.txt
FileWriter writer=new FileWriter(fileName);
writer.write("Hello wly:\n");
writer.write(" My name is wly!\n");
writer.write(" I like you and miss you。");
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
//注意:上面的例子由于写入的文本很少,使用FileWrite类就可以了。但如果需要写入的
//内容很多,就应该使用更为高效的缓冲器流类BufferedWriter。
/**
* 使用BufferedWriter类写文本文件
*/
public static void writeBufferedWriter(String fileName)
{
try
{
BufferedWriter out=new BufferedWriter(new FileWriter(fileName));
out.write("Hello wly:");
out.newLine(); //注意\n不一定在各种计算机上都能产生换行的效果
out.write(" My name is wly!\n");
out.write(" I like you and miss you。");
out.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 使用FileWriter类往文本文件中追加信息
*/
public static void writeFileWriter2(String fileName)
{
try
{
//使用这个构造函数时,如果存在kuka.txt文件,
//则直接往kuka.txt中追加字符串
FileWriter writer=new FileWriter(fileName,true);
SimpleDateFormat format=new SimpleDateFormat();
String time=format.format(new Date());
writer.write("\n\t"+time);
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 追加文件:使用RandomAccessFile(写入随机文件)
*/
public static void appendRandomAccessFile(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
9、复制文件
package utill;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import org.apache.commons.io.FileUtils;
public class fileUtill {
public static void main(String[] args) {
File source = new File("D:/file/flie.txt");
File dest = new File("D:/file1/flie.txt");
try {
copyFileUsingFileStreams(source,dest);
copyFileUsingFileChannels(source,dest);
copyFileUsingApacheCommonsIO(source,dest);
copyFileUsingJava7Files(source,dest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//使用FileStreams复制
private 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();
}
}
//使用FileInputStream/FileOutputStream字节流进行文件的复制操作
private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}
//使用Commons IO复制
private static void copyFileUsingApacheCommonsIO(File source, File dest)
throws IOException {
FileUtils.copyFile(source, dest);
}
//使用Java7的Files类复制
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
/**
* 利用字节流复制
* 使用BufferedInputStream/BufferedOutputStream高效字节流进行复制文件
*/
public static void copy(String source,String dest) throws IOException{
InputStream is = new BufferedInputStream(new FileInputStream(source));
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
//文件拷贝u,-- 循环+读取+写出
byte[] b = new byte[1024];//缓冲大小
int len = 0;//接收长度
//读取文件
while (-1!=(len = is.read(b))) {
//读入多少,写出多少,直到读完为止。
os.write(b,0,len);
}
//强制刷出数据
os.flush();
//关闭流,先开后关
os.close();
is.close();
}
/**
* 字符流复制
* 使用BufferedReader/BufferedWriter高效字符流进行文件复制(注意这种方式只能复制只包含字符的文件,也就意味着你用记事本打开该文件你能够读懂)
*/
public static void copy1(String source,String dest) throws IOException{
//字符输入流
BufferedReader reader = new BufferedReader(new FileReader(source));
//字符输出流
BufferedWriter writer = new BufferedWriter(new FileWriter(dest));
char[] cbuf = new char[1024];
int len = 0;
//边读入边写出
while ((len = reader.read(cbuf)) != -1) {
writer.write(cbuf, 0, len);
}
//关闭流
writer.close();
reader.close();
}
//使用FileReader/FileWriter字符流进行文件复制。(注意这种方式只能复制只包含字符的文件,也就意味着你用记事本打开该文件你能够读懂)
private static void readerWriterCopyFile(File source, File dest) throws IOException {
// 使用字符流进行文件复制,注意:字符流只能复制只含有汉字的文件
FileReader fr = new FileReader(source);
FileWriter fw = new FileWriter(dest);
Integer by = 0;
while((by = fr.read()) != -1) {
fw.write(by);
}
fr.close();
fw.close();
}
}
10、复制文件夹及文件夹中文件
package utill;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
public class fileUtill {
public static void main(String[] args) {
// File source = new File("D:/file");
// File dest = new File("D:/file1");
String source = "D:/file";
String dest = "D:/file1";
try {
//copyFolder(source,dest);
copyFolder2(source,dest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//---------------------------方法1-----------------------------------------
/**
* 复制文件夹/文件(仅复制单层无法递归)
*
* @param resource 源路径
* @param target 目标路径
*/
public static void copyFolder(String resource, String target) throws Exception {
File resourceFile = new File(resource);
if (!resourceFile.exists()) {
throw new Exception("源目标路径:[" + resource + "] 不存在...");
}
File targetFile = new File(target);
if (!targetFile.exists()) {
throw new Exception("存放的目标路径:[" + target + "] 不存在...");
}
// 获取源文件夹下的文件夹或文件
File[] resourceFiles = resourceFile.listFiles();
for (File file : resourceFiles) {
File file1 = new File(targetFile.getAbsolutePath() + File.separator + resourceFile.getName());
// 复制文件
if (file.isFile()) {
System.out.println("文件" + file.getName());
// 在 目标文件夹(B) 中 新建 源文件夹(A),然后将文件复制到 A 中
// 这样 在 B 中 就存在 A
if (!file1.exists()) {
file1.mkdirs();
}
File targetFile1 = new File(file1.getAbsolutePath() + File.separator + file.getName());
copyFile(file, targetFile1);
}
// 复制文件夹
if (file.isDirectory()) {// 复制源文件夹
String dir1 = file.getAbsolutePath();
// 目的文件夹
String dir2 = file1.getAbsolutePath();
copyFolder(dir1, dir2);
}
}
}
/**
* 复制文件
*
* @param resource
* @param target
*/
public static void copyFile(File resource, File target) throws Exception {
// 输入流 --> 从一个目标读取数据
// 输出流 --> 向一个目标写入数据
long start = System.currentTimeMillis();
// 文件输入流并进行缓冲
FileInputStream inputStream = new FileInputStream(resource);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
// 文件输出流并进行缓冲
FileOutputStream outputStream = new FileOutputStream(target);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
// 缓冲数组
// 大文件 可将 1024 * 2 改大一些,但是 并不是越大就越快
byte[] bytes = new byte[1024 * 2];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
// 刷新输出缓冲流
bufferedOutputStream.flush();
//关闭流
bufferedInputStream.close();
bufferedOutputStream.close();
inputStream.close();
outputStream.close();
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start) / 1000 + " s");
}
//---------------------------方法2-----------------------------------------
/**
* 复制文件夹/文件(仅复制单层无法递归)
*
* @param resource 源路径
* @param target 目标路径
*/
public static void copyFolder2(String resource, String target) throws IOException {
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(resource);
LinkedList<String> folderList2 = new LinkedList<String>();
folderList2.add(target+ resource.substring(resource.lastIndexOf("/")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() + File.separator
+ file[i]);
} else {
temp = new File(folderList.peek() + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator + (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
//System.out.println("复制整个文件夹内容失败!");
e.printStackTrace();
}
// folderList.removeFirst();
// folderList2.removeFirst();
folderList.clear();
folderList2.clear();
}
}
//---------------------------方法3-----------------------------------------
/**
* 复制文件夹/文件(递归)
*
* @param srcFolder 源路径
* @param destFolder 目标路径
*/
public static void copyFolder3(File srcFolder, File destFolder) throws IOException {
// TODO Auto-generated method stub
//判断该File是文件夹还是文件
if(srcFolder.isDirectory()){
//是文件夹
//在目的地创建相同目录
File newFolder = new File(destFolder,srcFolder.getName());
newFolder.mkdir();
//遍历该对象
File [] fileArray=srcFolder.listFiles();
for(File file:fileArray){
//递归文件夹
copyFolder3(file, newFolder);
}
}else{
//是文件
//递归出口
String name=srcFolder.getName();
File NewFile = new File(destFolder,name);
copy3(srcFolder,NewFile);
}
}
//复制文件
public static void copy3(File file, File newFile) throws IOException {
// TODO Auto-generated method stub
//创建字节流缓冲对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
//读写数据
byte [] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1){
bos.write(bys, 0, len);
}
//释放资源
bis.close();
bos.close();
}
}
11、移动文件夹及文件
package utill;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class fileUtill {
public static void main(String[] args) {
File source = new File("D:/file");
File dest = new File("D:/file1");
for (int i = 0; i < 5; i++) {
copy(source, dest);
}
File srcFile2 = new File("D:/file");
File srcFile3 = new File("D:/file/copy1");
File srcFile4 = new File("D:/file/copy2");
File dstDir2 = new File("D:/file");
move(srcFile2, dstDir2);
move(srcFile3, dstDir2);
move(srcFile4, dstDir2);
delete(srcFile2);
}
//------------------------------1-----------------------------------------
//移动指定文件
private static void moveTotherFolders(String resource,String target,String pathName){
String startPath = resource + File.separator + pathName;
String endPath = target + File.separator;
try {
File startFile = new File(startPath);
File tmpFile = new File(endPath);//获取文件夹路径
if(!tmpFile.exists()){//判断文件夹是否创建,没有创建则创建新文件夹
tmpFile.mkdirs();
}
System.out.println(endPath + startFile.getName());
if (startFile.renameTo(new File(endPath + startFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
} catch (Exception e) {
}
}
//------------------------------------------2----------------------------
// 删除某个目录及目录下的所有子目录和文件
public static boolean deleteDir(File Folders) {
// 如果是文件夹
if (Folders.isDirectory()) {
// 则读出该文件夹下的的所有文件
String[] children = Folders.list();
// 递归删除目录中的子目录下
for (int i = 0; i < children.length; i++) {
boolean isDelete = deleteDir(new File(Folders, children[i]));
// 如果删完了,没东西删,isDelete==false的时候,则跳出此时递归
if (!isDelete) {
return false;
}
}
}
// 读到的是一个文件或者是一个空目录,则可以直接删除
return Folders.delete();
}
/**
* 复制某个目录及目录下的所有子目录和文件到新文件夹
* @param resource 源目录
* @param target 目标目录
*/
public static void copyFolder(String resource, String target) {
try {
// 如果文件夹不存在,则建立新文件夹
(new File(target)).mkdirs();
// 读取整个文件夹的内容到file字符串数组,下面设置一个游标i,不停地向下移开始读这个数组
File filelist = new File(resource);
String[] file = filelist.list();
// 要注意,这个temp仅仅是一个临时文件指针
// 整个程序并没有创建临时文件
File temp = null;
for (int i = 0; i < file.length; i++) {
// 如果oldPath以路径分隔符/或者\结尾,那么则oldPath/文件名就可以了
// 否则要自己oldPath后面补个路径分隔符再加文件名
// 谁知道你传递过来的参数是f:/a还是f:/a/啊?
if (resource.endsWith(File.separator)) {
temp = new File(resource + file[i]);
} else {
temp = new File(resource + File.separator + file[i]);
}
// 如果游标遇到文件
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
// 复制并且改名
FileOutputStream output = new FileOutputStream(target
+ "/" + "rename_" + (temp.getName()).toString());
byte[] bufferarray = new byte[1024 * 64];
int prereadlength;
while ((prereadlength = input.read(bufferarray)) != -1) {
output.write(bufferarray, 0, prereadlength);
}
output.flush();
output.close();
input.close();
}
// 如果游标遇到文件夹
if (temp.isDirectory()) {
copyFolder(resource + "/" + file[i], target + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
}
}
public static void moveFolder(String oldPath, String newPath) {
// 先复制文件
copyFolder(oldPath, newPath);
// 则删除源文件,以免复制的时候错乱
deleteDir(new File(oldPath));
}
//----------------------------3-------------------------------------------
/**
* 移动(剪切)文件
*
* @param resource 源目录
* @param target 目标目录
* @return
*/
public static boolean moveFile(File resource, File target) {
if (!resource.exists() || resource.isDirectory()) {
return false;
}
if (!target.exists()) {
target.mkdirs();
}
String oldFileName = resource.getName();
File newFile = new File(target, oldFileName);
if (resource.renameTo(newFile)) {// 直接重命名绝对路径速度更快
return true;
} else {// 文件已经存在,需要自动编号复制再删除源文件
copyFile(resource, target);
resource.delete();
}
return true;
}
/**
* 移动文件或文件夹
* 如果目标文件夹不存在则自动创建
* 如果文件或文件夹已经存在则自动编号-copy n
* @param resource 源文件或文件夹绝对路径
* @param target 目标文件夹绝对路径
* @return 是否成功移动文件或文件夹
*/
public static boolean move(File resource, File target) {
if (!resource.exists()) {
return false;
}
if (!target.exists()) {
target.mkdirs();
}
if (resource.isFile()) {// 文件
moveFile(resource, target);
} else {// 文件夹
String oldSrcName = resource.getName();
int srcNumber = 0;
File newSrcDir = new File(target, oldSrcName);
while (newSrcDir.exists()) {
srcNumber++;
String newSrcName = oldSrcName + "-copy" + srcNumber;
newSrcDir = new File(target, newSrcName);
}
newSrcDir.mkdirs();
for (File srcSub : resource.listFiles()) {
move(srcSub, newSrcDir);// 递归移动源文件夹下子文件和文件夹
}
resource.delete();
}
return true;
}
/**
* 复制文件
* 从源路径到目标文件夹路径,文件名保持一致
* 如果目标文件夹不存在则自动创建
* 如果文件已经存在则自动编号-copy n
* @param resource 源文件绝对路径
* @param target 目标文件夹绝对路径
* @return 是否成功复制文件
*/
public static boolean copyFile(File resource, File target) {
if (!resource.exists() || resource.isDirectory()) {
return false;
}
if (!target.exists()) {
target.mkdirs();
}
String oldFileName = resource.getName();
Pattern suffixPattern = Pattern.compile("\\.\\w+");
Matcher matcher = suffixPattern.matcher(oldFileName);
String nameBody;
String suffix;
if (matcher.find()) {
nameBody = oldFileName.substring(0, matcher.start());
suffix = oldFileName.substring(matcher.start());
} else {
nameBody = oldFileName;
suffix = "";
}
int fileNumber = 0;
File newFile = new File(target, oldFileName);
while (newFile.exists()) {
fileNumber++;
String newFileName = nameBody + "-copy" + fileNumber + suffix;
newFile = new File(target, newFileName);
}
try {
FileChannel fileIn = new FileInputStream(resource).getChannel();
FileChannel fileOut = new FileOutputStream(newFile).getChannel();
fileIn.transferTo(0, fileIn.size(), fileOut);
fileIn.close();
fileOut.close();
} catch (IOException e) {
return false;
}
return true;
}
/**
* 复制文件或文件夹
* 如果目标文件夹不存在则自动创建
* 如果文件或文件夹已经存在则自动编号-copy n
* @param resource 源文件或文件夹绝对路径
* @param target 目标文件夹绝对路径
* @return 是否成功复制文件或文件夹
*/
public static boolean copy(File resource, File target) {
if (!resource.exists()) {
return false;
}
if (!target.exists()) {
target.mkdirs();
}
if (resource.isFile()) {// 文件
copyFile(resource, target);
} else {// 文件夹
String oldSrcName = resource.getName();
int srcNumber = 0;
File newSrcDir = new File(target, oldSrcName);
while (newSrcDir.exists()) {
srcNumber++;
String newSrcName = oldSrcName + "-copy" + srcNumber;
newSrcDir = new File(target, newSrcName);
}
newSrcDir.mkdirs();
for (File srcSub : resource.listFiles()) {
copy(srcSub, newSrcDir);// 递归复制源文件夹下子文件和文件夹
}
}
return true;
}
/**
* 删除文件或文件夹
* @param src 源文件或文件夹绝对路径
* @return 是否成功删除文件或文件夹
*/
public static boolean delete(File src) {
if (!src.exists()) {
return false;
}
if (src.isFile()) {
src.delete();
} else {
for (File srcSub : src.listFiles()) {
delete(srcSub);// 递归删除源文件夹下子文件和文件夹
}
src.delete();
}
return true;
}
}
12、以某个文件夹的框架在另一个目录创建对应空文件夹
package utill;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
public class fileUtill {
public static void main(String[] args) {
String source = "D:/file";
String dest = "D:/file1";
copyFolder(source,dest);
}
/**
* 以某个文件夹的框架在另一个目录创建对应空文件夹
* @param resource 源目录
* @param target 目标目录
*/
public static void copyFolder(String resource, String target) {
boolean b=false;//不创建空文件
ArrayList<String>folderList=new ArrayList<String>();
folderList.add(resource);
ArrayList<String>folderList2=new ArrayList<String>();
folderList2.add(target);
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator)){
temp=new File(folderList.get(j)+"/"+file[i]);
}
else{
temp=new File(folderList.get(j)+"/"+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
if (b) temp.createNewFile();
}
if(temp.isDirectory()){//如果是子文件夹
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹失败");
e.printStackTrace();
}
}
}
}
13、读取文件属性
package utill;
import java.io.File;
import java.util.Date;
public class fileUtill {
public static void main(String[] args) {
String source = "D:/file/flie.txt";
readerFile(source);
}
/**
* 读取文件属性
* @param resource 文件路径
*/
public static void readerFile(String resourceFile) {
// 文件属性的取得
File f = new File(resourceFile);
if (f.exists()) {
System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length());
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified()));
} else {
System.out.println(f.getName() + "的属性如下:");
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件的最后修改日期为:" + new Date(f.lastModified()));
}
if(f.canRead()){
System.out.println("Can be Read");
}
if(f.canWrite()){
System.out.println("Can be Write");
}
}
}
14、文件写入属性
package utill;
import java.io.File;
public class fileUtill {
public static void main(String[] args) {
String source = "D:/file/flie.txt";
WriteFile(source);
}
/**
* 文件写入属性
* @param resource 文件路径
*/
public static void WriteFile(String resourceFile) {
// 文件属性的取得
File filereadonly=new File(resourceFile);
try {
boolean b=filereadonly.setReadOnly();
System.out.println("设置只读模式成功");
}
catch (Exception e) {
System.out.println("拒绝写访问:"+e.getMessage());
}
}
}