【问题标题】:How to rename temporary text file to master text file and delete privious existed master file如何将临时文本文件重命名为主文本文件并删除先前存在的主文件
【发布时间】:2021-05-06 15:56:54
【问题描述】:

这段代码在插入后将更新的记录插入临时文件,因为它有更新的记录,所以必须将temporary.txt重命名为主文件。但是那个时候我想删除privious主文本..怎么办?存款模块。

public void insertIntoTempoFile(String uID,String uName,String mobNo,String depoAmt)
{   File f1= new File("C:\\Users\\hp\\Desktop\\BankReport\\temporary.txt");
    File f2= new File("C:\\Users\\hp\\Desktop\\BankReport\\master.txt");

    FileWriter fwTemp = null;
    
try {
    f1.createNewFile();

    
    fwTemp = new FileWriter(f1,true);
        
     fwTemp.write(uID);  
     fwTemp.write("#");
     fwTemp.write(uName);  
     fwTemp.write("#");
     fwTemp.write(mobNo);  
     fwTemp.write("#");
     fwTemp.write(depoAmt);  
     fwTemp.write("\n");
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

finally {
    try {
        fwTemp.close();
         
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

【问题讨论】:

  • 如果将文件重命名为现有路径,则有两种情况,1. 因文件已存在而失败或 2. 覆盖现有文件。我认为你应该这样做: 1. 编写你的临时文件(temp1)。 2. 将 master 重命名为 temp (temp2)。 3. 将 temp1 重命名为 master。 4.删除temp2或者如果失败则回滚temp2到master。
  • 它不起作用,我改变了方法,但它不应该..
  • 请建议..

标签: java file-handling


【解决方案1】:

以下代码将数据写入temporary.txt,如果没有异常,则将文件重命名为master.txt

public static void main(String[] args) {
    insertIntoTempoFile("123", "Garreth", "321", "345");
}

private static void insertIntoTempoFile(String uID, String uName, String mobNo, String depoAmt) {
    String directory = "C:\\Users\\hp\\Desktop\\BankReport\\";
    String sourceFilename = "temporary.txt";
    String targetFilename = "master.txt";

    Path sourcePath = Paths.get(directory + sourceFilename);

    String row = uID + "#" + uName + "#" + mobNo + "#" + depoAmt + "\n";

    try {
        Files.write(sourcePath, row.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        renameMasterFileIfExists(directory, sourceFilename, targetFilename);
    }
}

/**
 * Take a look here for more details https://mkyong.com/java/how-to-rename-file-in-java/
 */
private static void renameMasterFileIfExists(String directory, String sourceFilename, String targetFilename) {
    Path source = Paths.get(directory + sourceFilename);
    Path target = Paths.get(directory + targetFilename);

    try {
        Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多