JAVA FILE or I/O学习 - 补充CopyFiles功能

时间:2025-04-11 23:36:19
 public class CopyFiles
{
public static void main(String[] args)
{
CopyFiles copyFiles = new CopyFiles();
copyFiles.copyS("E:\\", "【 图 片 】", "E:\\cba");
}
public void copyS(String sourcePath,String name,String newPath)
{
File file = new File(sourcePath, name);
if (file.isDirectory())
{
//在新位置创建该文件夹
File fileDir = new File(newPath, name);
if (!fileDir.exists())
{
fileDir.mkdir();
System.out.println("复制文件夹:"+fileDir);
}
else {
JOptionPane.showMessageDialog(null, "新路径中已经存在该文件!\n"+fileDir, "复制文件 - 提示", JOptionPane.WARNING_MESSAGE);
return;
} //操作原位置文件夹中的文件、文件夹
File[] nextFiles = file.listFiles();
if (nextFiles.length == 0)
{
return;
}
else {
for (File fileNext : nextFiles)
{
copyS(file.getAbsolutePath(), fileNext.getName(), fileDir.getAbsolutePath());
}
}
}
else {
//复制文件
byte[] data = new byte[1024];
try
{
BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
File fileNew = new File(newPath, name);
if (fileNew.exists())
{
JOptionPane.showMessageDialog(null, "新路径中已经存在该文件!\n"+fileNew, "复制文件 - 提示", JOptionPane.WARNING_MESSAGE);
return;
}
fileNew.createNewFile();
System.out.println("复制文件:"+fileNew);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(fileNew));
while (input.read(data) != -1)
{
output.write(data); }
output.flush();
output.close();
input.close();
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}