2017-06-01 47 views
0

刪除現有的文件,我有這樣的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,我不明白爲什麼。那麼爲什麼我指向的文件不能被刪除?

+1

您是否已根據操作系統檢查您是否有權刪除該文件? –

+1

該文件可能正在被另一個進程使用。如果是這種情況,那麼直到過程「死亡」才能刪除它。 – cdaiga

+1

返回'false'而不是拋出適當的異常是我們應該使用在Java 7(路徑,路徑,文件等)中添加的文件系統API而不是'File'類的原因之一。看看https://docs.oracle.com/javase/tutorial/essential/io/delete.html,也許在[Why File sucks](http://java7fs.wikia.com/wiki/Why_File_sucks) – Pshemo

回答

0

這總是一個好的設計來處理周圍的任何類型的我的可能出現的錯誤/ 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

+0

它引發FileSystemException,所以是與權限有關的東西。問題是這個文件被一個正在運行的服務器使用,但是我需要在我需要時刪除這個文件(再次,它不會允許我這樣做,因爲服務器使用的是不能停止的) –

+1

爲什麼你把'Files.delete'改成'file.delete'? 'file'表明你想在'File'實例上調用'delete'方法,但'File'類沒有'delete(anotherLocation)'方法。在文檔中有'Files'類,它與'File'不同。 「文件」提供了諸如「刪除(位置)」之類的實用方法。 – Pshemo

+0

@Pshemo Opps我沒有意識到,試圖使用OP的變量'file' - 感謝您指出它! – Zakir

0

請確保您擁有該目錄及其下的所有權限。這取決於你的操作系統,如果是Linux,你可以運行chmod

另外請確保看到this它曾經幫助過我。

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