龙空技术网

java编程对文件操作

不断进步中 179

前言:

如今小伙伴们对“java判断文件夹是否存在”大约比较看重,各位老铁们都想要知道一些“java判断文件夹是否存在”的相关知识。那么小编也在网上收集了一些有关“java判断文件夹是否存在””的相关资讯,希望看官们能喜欢,兄弟们一起来学习一下吧!

方法1 java操作文件重名

File file=new File("C:/tt/123.io");

if(file.exists()) {

File newfile=new File(file.getParent()+File.separator+"123.xlsx");//创建新名字的抽象文件

if(file.renameTo(newfile)) {

System.out.println("重命名成功!"+File.separator);

}

else {

System.out.println("重命名失败!新文件名已存在");

}

}

else {

System.out.println("重命名文件不存在!");

}

方法2 Java文件重名后,不保留原有文件

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.StandardCopyOption;

public class test02 {

public static void main(String[] args) {

File in = new File("C:/tt/123.io"); // 资源文件夹

File out = new File("C:/tt/123.xlsx"); // 目标文件夹

try {

Files.copy(in.toPath(), out.toPath().resolve(in.getPath().toString().replace(".io", ".xlsx")),

StandardCopyOption.REPLACE_EXISTING); // 重命名为.txt 并且复制到out文件夹

} catch (IOException e) { // 因为在lambda表达式内,所以要包裹try catch

e.printStackTrace();

}

System.out.println(out.getPath());

}

方法3下面比较理想的文件操作,Java文件重名后,保留原有文件与文件内容

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileTest {

public static void main(String[] args) throws Exception {

String url1 = "C:\\tt\\123.io";// 源文件路径

String url2 = "C:\\tt\\123.xlsx";// 目标路径(复制到E盘,重命名为b.txt)

copy(url1, url2);//操作文件如下,内容一起跟着变更

}

private static void copy(String from, String to) throws Exception {

File fromFile = new File(from), toFile = new File(to);

FileInputStream fis = null;

FileOutputStream fos = null;

try {

fis = new FileInputStream(fromFile);

fos = new FileOutputStream(toFile);

int bytesRead;

byte[] buf = new byte[4 * 1024]; // 4K buffer

while ((bytesRead = fis.read(buf)) != -1) {

fos.write(buf, 0, bytesRead);

}

fos.flush();

fos.close();

fis.close();

} catch (IOException e) {

System.out.println("$$$$$$$$$$$$$$$");

}

System.out.println("复制文件:" + "\n" + "源路径:" + from + "\n" + "目标路径:"

+ to);

}

}

标签: #java判断文件夹是否存在