java 讀取,修改properties檔案,不改變檔案內容順序
FileInputStream input1 = new FileInputStream("/jdbc.properties");//讀取程式碼
SafeProperties safeProp1 = new SafeProperties();
safeProp1.load(input1);
String safe= safeProp1.getProperty("url");
input1.close();
重寫Properties類FileInputStream input = new FileInputStream("sso.properties");//修改程式碼 SafeProperties safeProp = new SafeProperties(); safeProp.load(input); input.close(); safeProp.setProperty("sso.server.urlprefix","測試"); FileOutputStream output = new FileOutputStream("sso.properties"); safeProp.store(output, null); output.close();
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* Created by 31767 on 2017/8/8.
*/
public class SafeProperties extends Properties {
private static final long serialVersionUID = 5011694856722313621L;
private static final String keyValueSeparators = "=: \t\r\n\f";
private static final String strictKeyValueSeparators = "=:";
private static final String specialSaveChars = "=: \t\r\n\f#!";
private static final String whiteSpaceChars = " \t\r\n\f";
private PropertiesContext context = new PropertiesContext();
public PropertiesContext getContext() {
return context;
}
public synchronized void load(InputStream inStream) throws IOException {
BufferedReader in;
in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
while (true) {
String line = in.readLine();
String intactLine = line;
if (line == null)
return;
if (line.length() > 0) {
int len = line.length();
int keyStart;
for (keyStart = 0; keyStart < len; keyStart++)
if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
break;
if (keyStart == len)
continue;
char firstChar = line.charAt(keyStart);
if ((firstChar != '#') && (firstChar != '!')) {
while (continueLine(line)) {
String nextLine = in.readLine();
intactLine = intactLine + "\n" + nextLine;
if (nextLine == null)
nextLine = "";
String loppedLine = line.substring(0, len - 1);
int startIndex;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++)
if (whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1)
break;
nextLine = nextLine.substring(startIndex, nextLine.length());
line = new String(loppedLine + nextLine);
len = line.length();
}
int separatorIndex;
for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) {
char currentChar = line.charAt(separatorIndex);
if (currentChar == '\\')
separatorIndex++;
else if (keyValueSeparators.indexOf(currentChar) != -1)
break;
}
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++)
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
if (valueIndex < len)
if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
valueIndex++;
while (valueIndex < len) {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
String value = (separatorIndex < len) ? line.substring(valueIndex, len) : "";
key = loadConvert(key);
value = loadConvert(value);
put(key, value, intactLine);
} else {
context.addCommentLine(intactLine);
}
} else {
context.addCommentLine(intactLine);
}
}
}
private String loadConvert(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
outBuffer.append('\t'); /* [email protected] */
else if (aChar == 'r')
outBuffer.append('\r'); /* [email protected] */
else if (aChar == 'n') {
/*
* [email protected] do not convert a \n to a line.separator
* because on some platforms line.separator is a String
* of "\r\n". When a Properties class is saved as a file
* (store()) and then restored (load()) the restored
* input MUST be the same as the output (so that
* Properties.equals() works).
*
*/
outBuffer.append('\n'); /* [email protected] [email protected] */
} else if (aChar == 'f')
outBuffer.append('\f'); /* [email protected] */
else
/* [email protected] */
outBuffer.append(aChar); /* [email protected] */
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
public synchronized void store(OutputStream out, String header) throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
if (header != null)
writeln(awriter, "#" + header);
List entrys = context.getCommentOrEntrys();
for (Iterator iter = entrys.iterator(); iter.hasNext();) {
Object obj = iter.next();
if (obj.toString() != null) {
writeln(awriter, obj.toString());
}
}
awriter.flush();
}
private static void writeln(BufferedWriter bw, String s) throws IOException {
bw.write(s);
bw.newLine();
}
private boolean continueLine(String line) {
int slashCount = 0;
int index = line.length() - 1;
while ((index >= 0) && (line.charAt(index--) == '\\'))
slashCount++;
return (slashCount % 2 == 1);
}
/*
* Converts unicodes to encoded \uxxxx and writes out any of the
* characters in specialSaveChars with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len * 2);
for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace)
outBuffer.append('\\');
outBuffer.append(' ');
break;
case '\\':
outBuffer.append('\\');
outBuffer.append('\\');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
if (specialSaveChars.indexOf(aChar) != -1)
outBuffer.append('\\');
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
}
/**
* Convert a nibble to a hex character
*
* @param nibble
* the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
}
/** A table of hex digits */
private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };
public synchronized Object put(Object key, Object value) {
context.putOrUpdate(key.toString(), value.toString());
return super.put(key, value);
}
public synchronized Object put(Object key, Object value, String line) {
context.putOrUpdate(key.toString(), value.toString(), line);
return super.put(key, value);
}
public synchronized Object remove(Object key) {
context.remove(key.toString());
return super.remove(key);
}
class PropertiesContext {
private List commentOrEntrys = new ArrayList();
public List getCommentOrEntrys() {
return commentOrEntrys;
}
public void addCommentLine(String line) {
commentOrEntrys.add(line);
}
public void putOrUpdate(PropertyEntry pe) {
remove(pe.getKey());
commentOrEntrys.add(pe);
}
public void putOrUpdate(String key, String value, String line) {
PropertyEntry pe = new PropertyEntry(key, value, line);
remove(key);
commentOrEntrys.add(pe);
}
public void putOrUpdate(String key, String value) {
PropertyEntry pe = new PropertyEntry(key, value);
int index = remove(key);
commentOrEntrys.add(index,pe);
}
public int remove(String key) {
for (int index = 0; index < commentOrEntrys.size(); index++) {
Object obj = commentOrEntrys.get(index);
if (obj instanceof PropertyEntry) {
if (obj != null) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
return index;
}
}
}
}
return commentOrEntrys.size();
}
class PropertyEntry {
private String key;
private String value;
private String line;
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public PropertyEntry(String key, String value) {
this.key = key;
this.value = value;
}
/**
* @param key
* @param value
* @param line
*/
public PropertyEntry(String key, String value, String line) {
this(key, value);
this.line = line;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String toString() {
if (line != null) {
return line;
}
if (key != null && value != null) {
String k = saveConvert(key, true);
String v = saveConvert(value, false);
return k + "=" + v;
}
return null;
}
}
}
public void addComment(String comment) {
if (comment != null) {
context.addCommentLine("#" + comment);
}
}
}
相關推薦
java 讀取,修改properties檔案,不改變檔案內容順序
FileInputStream input1 = new FileInputStream("/jdbc.properties");//讀取程式碼 SafeProperties safeProp1 = new SafeProperties();
git刪除遠端分支檔案,不改變本地檔案
git提交專案時候踩的Git的坑 經歷 由於剛開始沒有設定.gitignore檔案,導致專案中所有的檔案都被提交到了github上面,由此帶來的問題就是有些debug日誌也被提交了上去,對於團隊開發很不友好。 一個錯誤的嘗試 git rm -r --cached "fileName/direction
java讀取word文檔,提取標題和內容
replace schema all stack int fonts ooxml pid spa 使用的工具為poi,需要導入的依賴如下 <dependency> <groupId>org.apache.poi<
Next Cloud通過修改資料庫表,達到替換檔案而不改變分享的連結地址的效果,以及自定義分享連結地址
# Next Cloud如何通過修改資料庫表,達到替換檔案而不改變分享的連結地址的效果,以及自定義分享的連結地址 本文首發於我的個人部落格:https://chens.life/nextcloud-change-share-files.html ## 前言 本站 [失眠孤島](https://chens
java w3c解析xml檔案,獲取指定節點內容,讀取外部配置檔案。
原始碼: package com.ys.adage.utils; import com.ys.adage.message.CodeObjectResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.
ubuntu 掛載硬碟時,只能讀取檔案,不能寫入的解決辦法
最近用自己的硬碟當做儲存工具,突然發生了問題,就是隻能看硬盤裡的資料卻無法修改或者複製內容,查了好多辦法都不行,最後看到我掛載硬碟時,硬碟資料夾出現×號,這才想起來可能由於許可權問題,被設定為只讀模式,所以解決辦法自然就是給許可權啊: 1 pwd檢視硬碟的
java修改JPG圖片DPI 不改變解析度
package util; import java.awt.*; import java.awt.image.*; import java.io.*; import java.net.*; import javax.imageio.*; import jav
java讀取預設編碼是ansi的文字檔案時,解決中文亂碼問題
// 封裝文字檔案 File file = new File("d:/test11.txt"); // BufferedReader br = new BufferedReader(new FileR
java讀取系統Properties配置檔案利用執行緒實時監控配置檔案變化
package util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; imp
java建立檔案,並向檔案中寫入字串,讀取字串到螢幕
public class FileTest01 { public static void writeFileString() { File file = new File("E:\\zkn")
5.刪除數組arr的最後一個元素,不改變原數組,結果返回新數組。
cnblogs bsp pan arr ast 刪除 let del pop 方法一:slice()方法; var a=[1,5,‘ff‘,‘g‘,‘h‘,‘sd‘,‘g‘]; alert( deletelast(a)); function
RMAN遷移資料庫(不改變檔案目錄)
1、目標庫建立相應目錄mkdir -p /u01/app/oracle/oradata/orclmkdir -p /u01/app/oracle/fast_recovery_area/ORCLmkdir -p /u01/app/oracle/admin/orcl/{a,dp}dump 2、目標庫建立密碼檔案
java讀取txt文件,對字符串進行操作後導出txt文件
file 計算機 public iter 一次 cep 行數據 文件內容 txt文件 嘿嘿,代碼略為簡單,不再多做解釋,直接上碼! package org.lq.com.util; import java.io.File; import java.io.InputStre
兩種方法刪除github遠端倉庫裡的檔案(不改變本地倉庫)
方法一(假如你要刪除的資料夾在你的本地倉庫也存在): 前提:假如你要刪除的資料夾在你的本地倉庫也存在,當然你也可以直接在github客戶端把本地倉庫更新一下,這樣你的本地倉庫裡就有你要刪除的檔案了,然後你在刪除,就到了下一步。 直接在本地倉庫刪除那個檔案,這個時候你的github客戶端會捕捉
讀取txt檔案,生成csv檔案
最近做了個小程式,要求在同文件夾下的txt檔案,處理內容之後,生成csv檔案。 1 import java.io.*; 2 import java.util.ArrayList; 3 import java.util.List; 4 5 public class Simplify
解決方案:Java+selenium定位元素後,sendKeys()輸入的內容顯示不完整
一、執行環境:Java + selenium + chrome 二、問題描述: 使用XPath定位到元素後,使用sendKeys()輸入內容,在輸入框顯示出來的內容不完整,也就是與所輸入內容不一致。比如sendKeys()輸入的是18611372039,輸入後,只顯示部分數字,18611。
C++查詢字串中同樣的字元,並將其刪除不改變字串的順序。
輸入一個字串,找到相同的字元,將後面出現的字元刪除,不改變字串的順序。 例如: Hello -》Helo 人山人海 -》人山海 程式碼實現: #include <iostream> #include<string>
numpy的dtype,astype,b=np.array(a,dtype='int16')型別轉換,不改變長度
綜述: np型別的a如果直接修改如:a.dtype='int16',那麼直接會修改a,會導致長度的不一致,如果要直接修改則要採用astype方法如:b=a.astype('int16'),a保持不變,b的長度等於a,並且type由a變成了into6,或者呼叫b=np.array(a,dtype=
python中多執行緒開啟的兩種方式(內含有event的應用,即安全的機制,類似於java的等待喚醒機制,不會出現多個執行緒之間的錯亂問題)
event是類似於java中的等待喚醒機制,具體方法參照上一篇CSDN 下面來介紹開啟執行緒的第一種方式 #Filename:threading1.py #開啟執行緒的第一種方式 import threading import time event=threadin
Java如何用WriteUTF寫檔案,ReadUTF讀檔案
直接上樣例參考(附有部分說明): File fileName = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + “/test/test.levp”); FileOut