无法删除Java中的现有文件

时间:2017-06-01 18:54:54

标签: java

我有这个Java类

    package com.cf.utils;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.cf.CoreFaction;
import com.cf.faction.Faction;

import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;

public class FactionUtils {

    public static boolean saveFaction(Faction f) {
        if (Utils.isServer()) {
            JSONObject obj = new JSONObject();
            obj.put("Name", f.getName());
            obj.put("Owner", f.getOwner().toString());

            JSONArray members = new JSONArray();
            for (UUID u : f.getMembers()) {
                members.add(u.toString());
            }

            obj.put("Members", members);

            File dir = new File(DimensionManager.getCurrentSaveRootDirectory() + "/factions");
            if (!dir.exists())
                dir.mkdirs();

            try (FileWriter file = new FileWriter(
                    DimensionManager.getCurrentSaveRootDirectory() + "/factions/" + f.getName() + ".json")) {
                file.write(obj.toJSONString());
                file.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static void deleteFaction(Faction f) {
        if (Utils.isServer()) {
            File file = new File(DimensionManager.getCurrentSaveRootDirectory() + "/factions/" + f.getName() + ".json");
            if (file.exists()) {
                if(file.delete()) { //THIS RETURNS FALSE
                    for (UUID p : f.getMembers()) {
                        Utils.sendMessage(p, Utils.getTranslation("faction.disbanded", TextFormatting.RED));
                    }
                } else
                    Utils.sendMessage(f.getOwner(), Utils.getTranslation("faction.disband.error", TextFormatting.RED));

            } else
                System.out.println("Can't find the file");
        }
    }

    public static Faction getFaction(UUID player) {
        for (Faction f : getAllFactions()) {
            if (f.getMembers().contains(player))
                return f;
        }
        return null;
    }

    public static Faction getFaction(String name) {
        for (Faction f : getAllFactions()) {
            if (f.getName().equalsIgnoreCase(name))
                return f;
        }
        return null;
    }

    public static ArrayList<Faction> getAllFactions() {
        ArrayList<Faction> list = new ArrayList<Faction>();
        if (Utils.isServer()) {
            File dir = new File(DimensionManager.getCurrentSaveRootDirectory() + "/factions");
            if (!dir.exists())
                return list;
            File[] factions = dir.listFiles();
            for (File f : factions) {
                JSONParser parser = new JSONParser();

                try {
                    Object obj = parser.parse(new FileReader(f));
                    JSONObject jsonObject = (JSONObject) obj;

                    JSONArray members = (JSONArray) jsonObject.get("Members");
                    Faction faction = new Faction((String) jsonObject.get("Name"),
                            UUID.fromString((String) jsonObject.get("Owner")));
                    ArrayList<UUID> ids = new ArrayList<UUID>();
                    for (int i = 0; i < members.size(); i++) {
                        ids.add(UUID.fromString(members.get(i).toString()));
                    }
                    faction.setMembers(ids);
                    list.add(faction);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
}

当我调用方法deleteFaction时,我想删除一个特定文件,但是尽管file.exists()返回true,file.delete()返回false,我无法弄清楚原因。那么为什么我指向的文件无法删除?

3 个答案:

答案 0 :(得分:0)

处理本地或网络上任何类型的i / o可能出现的错误一直是一种很好的设计实践 尝试在delete()中捕获以下异常: -

try {
    Files.delete(file.toPath());
} catch (NoSuchFileException x) {
    System.err.format("%s: no such" + " file or directory%n", file.getAbsolutePath());
} catch (DirectoryNotEmptyException x) {
    System.err.format("%s not empty%n", file.getAbsolutePath());
} catch (IOException x) {
    // File permission problems are caught here.
    System.err.println(x);
}

这是Java documentation

答案 1 :(得分:0)

确保您对该目录及其下的所有内容拥有正确的权限。这取决于您的操作系统,如果是Linux,您可以运行chmod

另外请务必看一下this曾帮助过我。

答案 2 :(得分:0)

/**
     * Deletes the file or directory denoted by this abstract pathname.  If
     * this pathname denotes a directory, then the directory must be empty in
     * order to be deleted.
     *
     * @return  <code>true</code> if and only if the file or directory is
     *          successfully deleted; <code>false</code> otherwise
     *
     * @throws  SecurityException
     *          If a security manager exists and its <code>{@link
     *          java.lang.SecurityManager#checkDelete}</code> method denies
     *          delete access to the file
     */

您确定您的进程具有删除权限吗?尝试抓住SecurityException

相关问题