2017-09-09 11 views
1

我有一个代码,将节省一个字符串变量+ +字符串.properties文件 但将其保存为字符串,当我加载它再次编程该变量不再是变量 - 它只是一个字符串。【JAVA】如何阅读从Java name.properties变量和字符串的文件的文件名

如何做到 - >加载字符串+变量+字符串,并将其加载到我的Java代码形式文件name.properties中的一个变量?

String userNickname = api.getClientInfo(movedevent.getClientId()).getNickname(); 
String Text="[i]Welcome [/i][color=red][b]" + userNickname+ "[/b][/color][i] on channel"; 


Properties prop = new Properties(); 
    try { 
prop.setProperty("Text", Textregister); 

      File f = new File("server.properties"); 
      if(!f.exists()){ 
      PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8")), true); 

      prop.store(out, "Autoconfig"); 
      } 





     } catch (Exception io) { 
      io.printStackTrace(); 
     } 

然后将其加载到程序中。

InputStream input = null; 

      try { 


       BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("server.properties"), "UTF8")); 
       // load a properties file 
       prop.load(in); 

       // get the property value and print it out 
       Text= prop.getProperty("Textregister"); 
} catch (IOException ex) { 
       ex.printStackTrace(); 
      } finally { 
       if (input != null) { 
        try { 
         input.close(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 

欢迎“+ userNickname +”上通道 “

,但我想欢迎Mynickname上通道”

任何一个可以帮助?

+0

能否打印变量userNickname的内容只是为了确保该变量的实际内容是什么?这将不得不在设置值之后。 – Juan

+0

问题是当我把它放到name.properties然后我读它。我得到了“信道欢迎Hakens”,但如果别人加入同一信道,他从name.properties负荷后得到了相同的消息“欢迎Hakens信道”的Cuz userNickname它也不是一个可变的只有像欢迎字符串......在通道。 – Hakens

回答

0

如果要替换在运行时的名称,可以节省你的文字,如:

"[i]Welcome [/i][color=red][b] {USER-NAME} [/b][/color][i] on channel" 

,然后读取属性之后,你就会有这样的字符串变量Text,这样你就可以搜索并将其替换为已登录的用户:

String userNickname = api.getClientInfo(movedevent.getClientId()).getNickname(); 
Text.replaceAll("{USER-NAME}", userNickname); 

注意:replaceAll的第一个参数是一个正则表达式。也许'{'和'}'必须用双斜杠来逃脱。我没有测试它。

0

这不行

String userNickname = api.getClientInfo(movedevent.getClientId()).getNickname(); 
Text.replaceAll("{USER-NAME}", userNickname); 

但我把这个字符串变量和未来变化之后,在我的代码 - 它的工作原理

String userNickname = api.getClientInfo(movedevent.getClientId()).getNickname(); 
String variable = Text.replaceAll("\\{USER-NAME\\}", userNickname); 

非常非常感谢胡安的帮助!