2014-09-06 24 views
0

我需要將播放器數據寫入文件並讀取它,並且每當它保存時編輯數據。我對File I/O不太好,但是這裏是我的。重置文件數據

public class DirectoryMaker { 


    static BufferedWriter bw; 
    static int lvl = 1; 
    static int hp = 100; 

    public static void main(String[] args) throws IOException { 


     FileWriter fw; 



     File dir = new File("c:\\MyFile\\b\\stuff"); 
     if (!dir.exists()) { 
      if (dir.mkdirs()) { 
       System.out.println("Directory is created!"); 
      } else { 
       System.out.println("Failed to create directory!"); 
      } 

     } 




     String fileName="hi"; 
     File tagFile=new File(dir,fileName+".txt"); 
     if(!tagFile.exists()){ 
     try { 



      fw = new FileWriter(tagFile.getAbsoluteFile()); 
      bw = new BufferedWriter(fw); 
      bw.write("LEVEL: " + lvl + "\n"); 


      tagFile.createNewFile(); 
      bw.close(); 



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


     } 


     Scanner s = new Scanner(tagFile); 
     while(s.hasNextLine()) { 
      System.out.println(s.nextLine()); 

     } 
     System.exit(1); 
    } 
} 

使用此代碼,當它更改時,如何更新文件中的lvl int。這個int更新後,我需要添加其他人並閱讀它們。

+0

爲什麼重寫整個文件不是一個選項? – 2014-09-06 19:03:23

回答

0

如果你將數據作爲文本存儲在一個文件中,我強烈建議使用YAML,它很好地格式化你的數據,並且很容易檢索。另一種選擇是JSON文件,但我不太熟悉JSON。這是一種常用的YAML庫:https://code.google.com/p/snakeyaml/這是非常簡單的使用方法:

File f = ...; 
String s = "Me"; 
Yaml y = new Yaml(); 
BufferedWriter writer = new BufferedWriter(new FileWriter(f)); 
y.dump(Map.Entry<"Name",s>, writer); 
writer.Close(); 
BufferedReader in = new BufferedReader(new FileReader(f)); 
Map map = (Map) yaml.load(f); //Loads whole document 
String name = map.get("Name"); //Find the String with the key "Name" 
in.Close(); 

可能有一些改進,做出,但這大多隻是給你的功能的想法。