【问题标题】:Overwriting database file with another non-empty one用另一个非空文件覆盖数据库文件
【发布时间】:2012-05-15 04:20:33
【问题描述】:

我正在尝试这个覆盖文件:

File file = new File(importDir, dbFile.getName());
DataOutputStream output = new DataOutputStream(
new FileOutputStream(file, false));                 
output.close();

但它显然用一个新的空文件覆盖了一个旧文件,我的目标是用file提供的内容覆盖它

我该如何正确地做到这一点?

【问题讨论】:

    标签: java android file


    【解决方案1】:

    不幸的是,文件复制这样简单的操作在 Java 中并不明显。

    在 Java 7 中你可以使用 NIO util class Files 如下:

    Files.copy(from, to);
    

    否则它更难,而不是大量的代码,最好仔细阅读Standard concise way to copy a file in Java?

    【讨论】:

    • Android 无法与 Java 7 相比,并且似乎没有 java.nio.file
    • 我没有考虑android标签
    【解决方案2】:
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.print("Enter a file name to copy : ");
        str = br.readLine();
    
        int i;
        FileInputStream f1;
        FileOutputStream f2;
    
      try
      {
        f1 = new FileInputStream(str);
        System.out.println("Input file opened.");
      }
      catch(FileNotFoundException e)
      {
        System.out.println("File not found.");
        return;
      }
    
      try
      {
        f2 = new FileOutputStream("out.txt");    //    <---   out.txt  is  newly created file
        System.out.println("Output file created.");
      }
      catch(FileNotFoundException e)
      {
        System.out.println("File not found.");
        return;
      }
    
      do
      {
        i = f1.read();
        if(i != -1) f2.write(i);
      }while(i != -1);
      f1.close();
      f2.close();
      System.out.println("File successfully copied");
    

    【讨论】:

    • 我没有在您的问题中阅读有关数据库文件的信息,所以我在这里发布了这个答案
    • 试试看,我没有用数据库文件检查过
    【解决方案3】:

    你可以使用

    FileOutputStream fos = new FileOutpurStream(file);

    fos.write(string.getBytes());

    将创建新文件或如果已经存在则覆盖它的构造函数...

    【讨论】:

    • 是的...没有字符串可以获取字节
    • 我认为您不能直接复制文件..相反,您必须逐行读取并将其写入其他文件...
    【解决方案4】:

    就我而言,似乎最简单的方法是删除文件然后复制它

                if (appFile.exists()) {
                    appFile.delete();
                    appFile.createNewFile();
                    this.copyFile(backupFile, appFile);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2012-11-22
      • 2011-05-02
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多