【问题标题】:Switch the name of the file [duplicate]切换文件名[重复]
【发布时间】:2013-06-09 03:14:53
【问题描述】:

我有像 323423233 这样的文件名。

我想把文件名的最后2位加到前面和 将其设为 33/323423233 并为其添加扩展名(如 .doc)。

我可以用什么简单的语句来实现这一点?

【问题讨论】:

  • 您确定要在文件名中添加斜杠吗? :)
  • 必须是java吗? Shell 脚本更适合这种类型的任务。
  • 您可以粘贴您尝试过的代码吗?
  • 猜测:OP想要创建目录33并将文件放在该目录下
  • @DMc - 他可能也想创建目录。显然,OP 在指定他的要求(以及研究如何实现它们)方面做得很差。

标签: java


【解决方案1】:

这是 2013 年。这是 Java 7。这是 FilesPath 的时间。

基础目录:

final Path baseDir = Paths.get("/path/to/baseDir");

确定文件的子目录:

final String s = name.substring(name.length() - 2, name.length());

创建该目录:

final Path subDir = baseDir.resolve(s);
// Will not do anything if directory already exists...
// But will throw exception if unable to create
Files.createDirectories(subDir);

写入文件:

final Path dst = subDir.resolve(name + ".doc");
Files.copy(src, dst);

删除原件:

Files.delete(src);

或者在一个操作中:

Files.move(src, dst);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2011-03-19
    • 1970-01-01
    • 2016-07-21
    相关资源
    最近更新 更多