首页 > 编程知识 正文

java文件设置文件名,java在指定路径生成文件

时间:2023-05-05 16:55:46 阅读:213767 作者:2580

/** * 通过文件路径直接修改文件名 * * @param filePath 需要修改的文件的完整路径 * @param newFileName 需要修改的文件的名称 * @return */ private String changeFileName(String filePath, String newFileName) { File f = new File(filePath); if (!f.exists()) { // 判断原文件是否存在(防止文件名冲突) return null; } newFileName = newFileName.trim(); if ("".equals(newFileName) || newFileName == null) // 文件名不能为空 return null; String newFilePath = null; if (f.isDirectory()) { // 判断是否为文件夹 newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName; } else { newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName + filePath.substring(filePath.lastIndexOf(".")); } File nf = new File(newFilePath); try { f.renameTo(nf); // 修改文件名 } catch (Exception e) { e.printStackTrace(); return null; } return newFilePath; }

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。