/**
* 文件重命名
* @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 + " 文件不存在,请检查文件是否被移除");
}
}
文件操作
最新推荐文章于 2024-10-23 22:33:41 发布