这是我编写的用于删除文件的代码(如果文件已经存在)
public void createFile(Map<String, String> map, String name)
{
try
{
System.out.println("Creating new File...");
File file = new File("./Analysis/files/master.csv");
if (file.exists())
{
System.out.println("File Deleted...."+file.delete());
}
System.out.println("New File Created "+file.createNewFile());
FileWriter fw = new FileWriter(file, true);
for (Map.Entry<String, String> entry : map.entrySet())
{
fw.write(entry.getKey());
fw.write(",");
fw.write(entry.getValue());
fw.write("\n");
fw.flush();
}
fw.close();
}catch(IOException e)
{
throw new BuildException(e.getMessage());
}
}
此file.exists对于该路径中已存在的文件显示为false,因此它不会删除该文件并将内容附加到该文件。任何想法?
答案 0 :(得分:3)
如果你改变了
FileWriter fw = new FileWriter(file, true);
到
FileWriter fw = new FileWriter(file, false);
它不会附加文字而是粘贴新的
编辑:
public void createFile(Map<String, String> map, String name)
{
try
{
File file = new File("./Analysis/files/master.csv");
FileWriter fw = new FileWriter(file, false);
for (Map.Entry<String, String> entry : map.entrySet())
{
fw.write(entry.getKey());
fw.write(",");
fw.write(entry.getValue());
fw.write("\n");
fw.flush();
}
fw.close();
}catch(IOException e)
{
throw new BuildException(e.getMessage());
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
FileWriter将使用规范文件表单来创建您的文件。因此,请对同一表格执行检查,看看是否符合您的期望。
将代码的前两行更改为:
File file = new File("./Analysis/files/master.csv").getCanonicalFile();
System.out.println("Creating new File "+ file.getAbsolutePath());