文件操作

本文介绍了文件操作中的核心方法,包括文件重命名、剪切及复制等,并提供了详细的实现步骤和异常处理方式。通过这些方法,可以高效地进行文件管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
* 文件重命名
* @param from 源文件
* @param fileName 修改后的文件名
* @throws IOException
*/
public void fileRename(String from, String fileName) throws IOException
{
//检查文件是否存在
fileExists(from);

//得到文件路径后组合新文件路径
File file = new File(from);
String path = file.getParent();
String filePath = path + fileName;

file.renameTo(new File(filePath));
}

/**
* 剪切文件
* @param from 剪切文件路径
* @param to 存放文件路径
* @throws IOException
*/
public void fileCut(String from, String to) throws IOException
{
//检查文件正确性
fileCheck(from, to);

//拷贝文件
fileCopy(from, to);

//删除原文件
File toFile = new File(from);
toFile.delete();
}

/**
* 复制文件
* @param from 复制文件路径
* @param to 存放文件路径
* @throws IOException
*/
public void fileCopy(String from, String to) throws IOException
{
//检查文件正确性
fileCheck(from, to);

//拷贝文件
InputStream in = new FileInputStream(from);
byte[] b = new byte[in.available()];
in.read(b);
in.close();

//粘贴文件
OutputStream out = new FileOutputStream(to);
out.write(b);
out.flush();
out.close();
}

/**
* 检查文件正确性
* @param from
* @param to
* @throws IOException
*/
private void fileCheck(String from, String to) throws IOException
{
File fromFile = new File(from);
File toFile = new File(to);

//如果被复制文件不存在或者不是文件
if(!fromFile.exists() || !fromFile.isFile())
{
throw new FileNotFoundException(from + " 文件不存在,请检查文件是否被移除");
}

//如果存放的文件名存在
if(toFile.exists())
{
throw new IOException(to + " 文件名已存在,请重新输入文件名");
}
}

/**
* 检查文件是否存在
* @param file
* @return
* @throws IOException
*/
public void fileExists(String filePath) throws IOException
{
File file = new File(filePath);
//如果存放的文件名存在
if(!file.exists() || !file.isFile())
{
throw new FileNotFoundException(file + " 文件不存在,请检查文件是否被移除");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值