【发布时间】:2016-11-09 07:29:41
【问题描述】:
我在 Mac 上编写了我的代码。 我正在创建两个文件,我们称它们为 file1 和 file2 对于file1,如果我在SQL 中发现一个表的记录比存储在file1 中的记录更大,我将所有内容写入一个临时文件,删除file1 并将临时文件重命名为file1。这适用于 Windows 和 Mac。
对于 file2,如果我在 SQL 中发现表的时间戳值大于存储在 file2 中的时间戳值,我会执行相同的过程。这在我的 Mac 环境中本地运行,但无法在 Windows 上删除和重命名文件。
但是,当我第一次启动程序时,由于我的缓冲写入器总是写入临时文件,然后重命名临时文件,所以在我第一次运行程序时,文件 2 的重命名和删除工作,这意味着文件 2 并且两者都没有file1 还存在。
所以在启动时,file2 不存在。缓冲写入器写入 tempFile,如果存在则删除 file2(在本例中不存在),并将 tempFile 重命名为 file2。这行得通。然而,新数据的后续记录无法删除和重命名文件 2。但正如我所说,这适用于 Mac,但不适用于 Windows。
删除和重命名文件 1 的代码(适用于 windows 和 Mac):
private void recordMaxRecordIdFromHistory(String table, String maxRecord) {
String line;
try {
File file1 = new File(file1);
File tempFile = new File("tempFile.txt");
FileWriter fw = new FileWriter(tempFile, false);
BufferedWriter bw = new BufferedWriter(fw);
if (!file1.exists()) {
file1.createNewFile();
}
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
//writing to temp file
if(){
....
}
else{
....
}
bw.close();
br.close();
if (file1.delete()) {
logger.info("Successfully deleted the max ID file");
} else {
logger.error("Unable to delete the file maxID File");
}
if (tempFile.renameTo(file1)) {
logger.info("Successfully renamed the tempFile to file1");
} else {
logger.error("Unable to rename the tempFile to file1");
}
} catch (Exception ex) {
logger.error(ex.getMessage());
}
}
删除和重命名 File2 的代码(适用于 Mac,并且仅在第一次在 Windows 上运行程序时)
private void recordLastModifiedDate(String table, Timestamp modifiedDate) {
String line;
try {
File file2 = new File(file2);
File tempFile2 = new File("tempFile2.txt");
FileWriter fw = new FileWriter(tempFile2, false);
BufferedWriter bw = new BufferedWriter(fw);
if (!file2.exists()) {
file2.createNewFile();
}
FileReader fr = new FileReader(file2);
BufferedReader br = new BufferedReader(fr);
//WRITING TO FILE HERE
bw.close();
br.close();
if (file2.delete()) {
logger.info("Successfully deleted the lastModified file");
} else {
logger.error("Unable to delete the lastModified file");
}
if (tempFile2.renameTo(file2)) {
logger.info("Successfully renamed the tempFile to lastModified");
} else {
logger.error("Unable to rename the tempFile to lastModified");
}
} catch (Exception ex) {
logger.error(ex.getMessage());
}
}
【问题讨论】:
-
这与标签batch-file有什么关系?请在应用标签之前阅读标签信息!
-
这与批处理文件标签无关。我已经删除了它。标签在这里有特定的含义。请不要随意添加那些听起来很熟悉的内容。在使用任何标签之前阅读说明,以确保它适合您的问题。如果您不确定,请不要添加它,如果需要,这里有人会为您添加它。谢谢。