2013-08-01 22 views
4

我在Java工作,但我確信這個問題擴展到多種其他語言和情況。從外部.txt文件流入大字符串還是直接在其中直接編碼是更智能的?

如果我定期在JTextPane顯示文本的大塊,

是更好地把它們寫入到一個文本文件,並定期呼籲 一個掃描器讀取所述文件,把它扔進了JTextPane,

或應該 我只是將文本直接寫入我的代碼中作爲字符串,然後將它們顯示在JTextPane中?

一種方法比另一種更合適嗎?我知道「將它寫入代碼」方法最終會給我巨大的方法和一些比我習慣的更醜陋的代碼。但是,某些情況下需要包含或排除不同位數的文本。

如果所需的應用程序使問題更容易回答,我正在使用RPG元素進行基於文本的冒險以練習我的Java編碼。根本不是專業,只是概念練習。因此,我必須在大量的講故事和更小的問題和情況之間切換,這取決於玩家以前的選擇。

我是新來的,不得不處理我的編碼中的大量文字,所以謝謝所有回答!

回答

4

把它放在一個單獨的文件裏,最好是在JAR本身,所以你可以通過getResourceAsStream()輕鬆找到它。

然後,您可以輕鬆地編輯此文件而不會混淆代碼,並且還可以在將應用程序編譯爲JAR之後對其進行修改。

一般來說,將邏輯與數據分開是一種很好的做法。


以下是你可能想從我的文件實用程序類的一些方法:

public static String streamToString(InputStream in) { 

    BufferedReader br = null; 
    StringBuilder sb = new StringBuilder(); 

    String line; 
    try { 

     br = new BufferedReader(new InputStreamReader(in)); 
     while ((line = br.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 

    } catch (IOException e) { 
     Log.e(e); 
    } finally { 
     if (br != null) { 
      try { 
       br.close(); 
      } catch (IOException e) { 
       Log.e(e); 
      } 
     } 
    } 

    return sb.toString(); 
} 


public static InputStream stringToStream(String text) { 

    try { 
     return new ByteArrayInputStream(text.getBytes("UTF-8")); 
    } catch (UnsupportedEncodingException e) { 
     Log.e(e); 
     return null; 
    } 
} 


public static InputStream getResource(String path) { 

    return FileUtils.class.getResourceAsStream(path); 
} 

你也可以使用一個SimpleConfig類從文件中解析列表和地圖:
(註釋掉Log.something調用並替換爲System.err.println())

package net.mightypork.rpack.utils; 


import java.io.File; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.LinkedHashMap; 
import java.util.List; 
import java.util.Map; 
import java.util.Map.Entry; 


/** 
* Utility for parsing simple config files<br> 
* # and // mark a comment<br> 
* empty lines and lines without "=" are ignored<br> 
* lines with "=" must have "key = value" format, or a warning is logged.<br> 
* use "NULL" to create empty value. 
* 
* @author MightyPork 
*/ 
public class SimpleConfig { 

    /** 
    * Load list from file 
    * 
    * @param file file 
    * @return map of keys and values 
    * @throws IOException 
    */ 
    public static List<String> listFromFile(File file) throws IOException { 

     String fileText = FileUtils.fileToString(file); 

     return listFromString(fileText); 
    } 


    /** 
    * Load map from file 
    * 
    * @param file file 
    * @return map of keys and values 
    * @throws IOException 
    */ 
    public static Map<String, String> mapFromFile(File file) throws IOException { 

     String fileText = FileUtils.fileToString(file); 

     return mapFromString(fileText); 
    } 


    /** 
    * Load list from string 
    * 
    * @param text text of the file 
    * @return map of keys and values 
    */ 
    public static List<String> listFromString(String text) { 

     List<String> list = new ArrayList<String>(); 

     String[] groupsLines = text.split("\n"); 

     for (String s : groupsLines) { 
      // ignore invalid lines 
      if (s.length() == 0) continue; 
      if (s.startsWith("#") || s.startsWith("//")) continue; 

      // NULL value 
      if (s.equalsIgnoreCase("NULL")) s = null; 

      if (s != null) s = s.replace("\\n", "\n"); 

      // save extracted key-value pair 
      list.add(s); 
     } 

     return list; 
    } 


    /** 
    * Load map from string 
    * 
    * @param text text of the file 
    * @return map of keys and values 
    */ 
    public static Map<String, String> mapFromString(String text) { 

     LinkedHashMap<String, String> pairs = new LinkedHashMap<String, String>(); 

     String[] groupsLines = text.split("\n"); 

     for (String s : groupsLines) { 
      // ignore invalid lines 
      if (s.length() == 0) continue; 
      if (s.startsWith("#") || s.startsWith("//")) continue; 
      if (!s.contains("=")) continue; 

      // split and trim 
      String[] parts = s.split("="); 
      for (int i = 0; i < parts.length; i++) { 
       parts[i] = parts[i].trim(); 
      } 

      // check if both parts are valid 
      if (parts.length == 0) { 
       Log.w("Bad line in config file: " + s); 
       continue; 
      } 

      if (parts.length == 1) { 
       parts = new String[] { parts[0], "" }; 
      } 

      if (parts.length != 2) { 
       Log.w("Bad line in config file: " + s); 
       continue; 
      } 


      // NULL value 
      if (parts[0].equalsIgnoreCase("NULL")) parts[0] = null; 
      if (parts[1].equalsIgnoreCase("NULL")) parts[1] = null; 

      if (parts[0] != null) parts[0] = parts[0].replace("\\n", "\n"); 
      if (parts[1] != null) parts[1] = parts[1].replace("\\n", "\n"); 

      // save extracted key-value pair 
      pairs.put(parts[0], parts[1]); 
     } 

     return pairs; 
    } 


    /** 
    * Save map to file 
    * 
    * @param target 
    * @param data 
    * @throws IOException 
    */ 
    public static void mapToFile(File target, Map<String, String> data) throws IOException { 

     String text = ""; //# File written by SimpleConfig 

     for (Entry<String, String> e : data.entrySet()) { 
      if (text.length() > 0) text += "\n"; 

      String key = e.getKey(); 
      String value = e.getValue(); 

      if (key == null) key = "NULL"; 
      if (value == null) value = "NULL"; 

      key = key.replace("\n", "\\n"); 
      value = value.replace("\n", "\\n"); 

      text += key + " = " + value; 
     } 

     FileUtils.stringToFile(target, text); 

    } 


    /** 
    * Save list to file 
    * 
    * @param target 
    * @param data 
    * @throws IOException 
    */ 
    public static void listToFile(File target, List<String> data) throws IOException { 

     String text = ""; //# File written by SimpleConfig 

     for (String s : data) { 
      if (text.length() > 0) text += "\n"; 

      if (s == null) s = "NULL"; 

      s = s.replace("\n", "\\n"); 

      text += s; 
     } 

     FileUtils.stringToFile(target, text); 

    } 
} 
+1

不錯的實用程序,但是當您將整個文件讀入內存時,它們會出現大文本文件失敗。儘管如此,仍然適用於這類問題。 –

+2

是的,我從來沒有用它來做任何大於幾千字節的事情,但我認爲對於大多數實際應用來說,它們就足夠了。 – MightyPork

2

最好有單獨的文件。其中一個原因是,在某個時候,你希望能夠將你的遊戲翻譯成不同的語言。

相關問題