另存为java文件

时间:2014-02-14 11:15:19

标签: java io

我有一个

 File file = new File("/home/aa.db");

然后我致电file.delete();

但我喜欢在删除之前保存此文件,并在其他位置使用其他名称。 - 如何在没有任何可视化工具的情况下在代码中进行操作?

我需要一份副本 - 因为我需要删除init文件。重命名不会做的事情

2 个答案:

答案 0 :(得分:1)

这里是将文件移动到新目录的示例 -

File file = new File("/home/aa.db");
File dir = new File("dir");

if (file.renameTo(new File(dir, file.getName()))) {
    // processing here
}

相关示例:

import java.io.File;

public class Example {
    public static void main(String[] args) {

        File file = new File("C://aa.db");
        File tmpFile = new File("C://temp", file.getName());

        if(file.renameTo(tmpFile)) {
            if(tmpFile.delete()) {
                System.out.println(tmpFile.getName() + " was deleted!");
            } else {
                System.out.println("Delete operation failed.");
            }
        }
    }
}

输出: aa.db was deleted!

答案 1 :(得分:0)

InputStream中阅读文件数据(您的需要),然后使用File

的此功能
public static long copy(InputStream in,Path target,CopyOption... options)
                 throws IOException
  

将输入流中的所有字节复制到文件中。返回时,输入   流将在流的末尾。

在此之前,首先需要创建要复制数据的目标路径。