할 수 있습니다.네트워크 상태 및 분석 properties 파일을 해당하는 Java 속성 클?
-
20-08-2019 - |
문제
이 있는 쉬운 방법은 C#을 읽기 속성이 있는 파일을 각 객실에는 별도의 라인을 따라 등호와 값을 다음과 같:
ServerName=prod-srv1
Port=8888
CustomProperty=Any value
Java,속성 클래스에 핸들이 구문 분석 쉽게:
Properties myProperties=new Properties();
FileInputStream fis = new FileInputStream (new File("CustomProps.properties"));
myProperties.load(fis);
System.out.println(myProperties.getProperty("ServerName"));
System.out.println(myProperties.getProperty("CustomProperty"));
나는 쉽게 로드할 수 있는 파일에서는 C#parse 각 라인,하지만 거기에 건설하는 방법을 쉽게 얻을 제공하지 않고 분석 키 이름과 같 표시겠어요?C#정보를 내가 찾는 것을 항상 은혜 XML 지만,이는 기존 파일에는 내가 제어하지 않고요 그것을 유지하는 기존 형식으로 필요합니다 더 많은 시간을 얻을 다른 팀을 변경하는 XML 구문 분석하는 기존 파일을 변경할 수 있습니다.
해결책
이에 대한 내장 지원은 없습니다.
당신은 자신의 "inifilereader"를 만들어야합니다. 아마도 이렇게?
var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));
Console.WriteLine(data["ServerName"]);
편집 : Paul의 의견을 반영하도록 업데이트되었습니다.
다른 팁
대부분의 Java ".properties"파일은 "="가 분리기라고 가정하여 분할 될 수 있지만 형식은 그보다 훨씬 더 복잡하고 그 공간, 동등한, 최신 및 속성 이름 또는 값의 유니 코드 문자를 포함시킬 수 있습니다.
C# 애플리케이션에 일부 Java 속성을로드해야하므로 Javaproperties.cs를 구현하여 Java 버전과 동일한 접근 방식을 사용하여 ".properties"포맷 된 파일을 올바르게 읽고 쓸 수 있습니다. http://www.kajabity.com/index.php/2009/06/load-java-properties-files-in-csharp/.
여기에서 클래스의 C# 소스가 포함 된 zip 파일과 테스트 한 일부 샘플 속성 파일을 찾을 수 있습니다.
즐기다!
최종 수업. 감사 @exxl.
public class Properties
{
private Dictionary<String, String> list;
private String filename;
public Properties(String file)
{
reload(file);
}
public String get(String field, String defValue)
{
return (get(field) == null) ? (defValue) : (get(field));
}
public String get(String field)
{
return (list.ContainsKey(field))?(list[field]):(null);
}
public void set(String field, Object value)
{
if (!list.ContainsKey(field))
list.Add(field, value.ToString());
else
list[field] = value.ToString();
}
public void Save()
{
Save(this.filename);
}
public void Save(String filename)
{
this.filename = filename;
if (!System.IO.File.Exists(filename))
System.IO.File.Create(filename);
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
foreach(String prop in list.Keys.ToArray())
if (!String.IsNullOrWhiteSpace(list[prop]))
file.WriteLine(prop + "=" + list[prop]);
file.Close();
}
public void reload()
{
reload(this.filename);
}
public void reload(String filename)
{
this.filename = filename;
list = new Dictionary<String, String>();
if (System.IO.File.Exists(filename))
loadFromFile(filename);
else
System.IO.File.Create(filename);
}
private void loadFromFile(String file)
{
foreach (String line in System.IO.File.ReadAllLines(file))
{
if ((!String.IsNullOrEmpty(line)) &&
(!line.StartsWith(";")) &&
(!line.StartsWith("#")) &&
(!line.StartsWith("'")) &&
(line.Contains('=')))
{
int index = line.IndexOf('=');
String key = line.Substring(0, index).Trim();
String value = line.Substring(index + 1).Trim();
if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
(value.StartsWith("'") && value.EndsWith("'")))
{
value = value.Substring(1, value.Length - 2);
}
try
{
//ignore dublicates
list.Add(key, value);
}
catch { }
}
}
}
}
샘플 사용 :
//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()
나는 파일 내에서 Emty Line, Occommenting and Pitcing을 허용하는 메소드를 작성했습니다.
예 :
var1 = "value1"
var2 = 'value2'
'var3 = 추측
; var4 = 추천
방법은 다음과 같습니다.
public static IDictionary ReadDictionaryFile(string fileName)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (string line in File.ReadAllLines(fileName))
{
if ((!string.IsNullOrEmpty(line)) &&
(!line.StartsWith(";")) &&
(!line.StartsWith("#")) &&
(!line.StartsWith("'")) &&
(line.Contains('=')))
{
int index = line.IndexOf('=');
string key = line.Substring(0, index).Trim();
string value = line.Substring(index + 1).Trim();
if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
(value.StartsWith("'") && value.EndsWith("'")))
{
value = value.Substring(1, value.Length - 2);
}
dictionary.Add(key, value);
}
}
return dictionary;
}
오래된 질문 (2009 년 1 월)에 대한 또 다른 답변 (2018 년 1 월).
Java Properties 파일의 사양은 Javadoc에 설명되어 있습니다. java.util.properties.load (java.io.reader)
. 한 가지 문제는 사양이 우리가 가질 수있는 첫인상보다 약간 복잡하다는 것입니다. 또 다른 문제는 여기에 일부 답변이 임의로 추가 사양을 추가했다는 것입니다. ;
그리고 '
댓글 라인의 우선으로 간주되지만 그렇지 않아야합니다. 속성 값에 대한 이중/단일 인용문은 제거되지만 그렇지 않아야합니다.
다음은 고려해야 할 사항입니다.
- 두 가지 종류의 선이 있습니다. 자연 선 그리고 논리적 라인.
- 자연 선은 종료됩니다
\n
,\r
,\r\n
또는 스트림의 끝. - 백 슬래시 문자로 라인 터미네이터 시퀀스를 피하여 논리 라인이 여러 인접한 자연 라인에 퍼질 수 있습니다.
\
. - 두 번째 시작시 공백과 논리적 선의 자연 선을 따르는 모든 공백은 폐기됩니다.
- 흰색 공간은 공간입니다 (
,
\u0020
), 탭 (\t
,\u0009
) 및 양식 공급 (\f
,\u000C
). - 사양에 명시 적으로 언급 된 바와 같이 "라인 터미네이터 시퀀스 앞에있는 캐릭터 만 검사하기 위해서는 라인 터미네이터가 탈출되었는지 결정하기 위해 라인 터미네이터 시퀀스 앞에있는 캐릭터 만 검사하는 것만으로는 충분하지 않습니다. 라인 터미네이터가 탈출 할 수있는 홀수의 연속 백 슬래시가 있어야합니다. 입력이 왼쪽에서 오른쪽으로 처리되므로 , 라인 터미네이터 (또는 다른 곳) 이전의 2N 연속 백 슬래시의 0이 아닌 균일 한 수의 짝수는 탈출 처리 후 N 백 슬래시를 인코딩합니다. "
=
키와 값의 분리기로 사용됩니다.:
키와 값 사이의 분리기로도 사용됩니다.- 키와 값 사이의 분리기를 생략 할 수 있습니다.
- 의견 라인이 있습니다
#
또는!
백인이 아닌 공간 캐릭터로서, 이전에 흰색 공간을 선도하는 것을 의미합니다.#
또는!
허용됩니다. - 주석선은 다음 자연 라인으로 확장 할 수 없습니다. 라인 터미네이터도
\
. - 사양에 명시 적으로 언급 된 바와 같이
=
,:
백 슬래시로 탈출하면 흰색 공간이 열쇠에 내장 될 수 있습니다. - 라인 터미네이터 문자도 사용하여 포함 할 수 있습니다
\r
그리고\n
탈출 시퀀스. - 값을 생략하면 빈 문자열이 값으로 사용됩니다.
\uxxxx
유니 코드 문자를 나타내는 데 사용됩니다.- 비 밸리에도 탈출 문자 이전의 백 슬래시 문자는 오류로 취급되지 않습니다. 조용히 떨어졌습니다.
예를 들어, If test.properties
다음 내용이 있습니다.
# A comment line that starts with '#'.
# This is a comment line having leading white spaces.
! A comment line that starts with '!'.
key1=value1
key2 : value2
key3 value3
key\
4=value\
4
\u006B\u0065\u00795=\u0076\u0061\u006c\u0075\u00655
\k\e\y\6=\v\a\lu\e\6
\:\ \= = \\colon\\space\\equal
다음 키 값 쌍으로 해석해야합니다.
+------+--------------------+
| KEY | VALUE |
+------+--------------------+
| key1 | value1 |
| key2 | value2 |
| key3 | value3 |
| key4 | value4 |
| key5 | value5 |
| key6 | value6 |
| : = | \colon\space\equal |
+------+--------------------+
PropertiesLoader
수업 authlete.authlete Nuget 패키지는 사양의 형식을 해석 할 수 있습니다. 아래 예제 코드 :
using System;
using System.IO;
using System.Collections.Generic;
using Authlete.Util;
namespace MyApp
{
class Program
{
public static void Main(string[] args)
{
string file = "test.properties";
IDictionary<string, string> properties;
using (TextReader reader = new StreamReader(file))
{
properties = PropertiesLoader.Load(reader);
}
foreach (var entry in properties)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
}
}
}
이 출력을 생성합니다.
key1 = value1
key2 = value2
key3 = value3
key4 = value4
key5 = value5
key6 = value6
: = = \colon\space\equal
Java의 동등한 예는 다음과 같습니다.
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String[] args) throws IOException
{
String file = "test.properties";
Properties properties = new Properties();
try (Reader reader = new FileReader(file))
{
properties.load(reader);
}
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
System.out.format("%s = %s\n", entry.getKey(), entry.getValue());
}
}
}
소스 코드, PropertiesLoader.cs
, 찾을 수 있습니다 authlete-csharp. xunit 테스트 PropertiesLoader
작성되었습니다 PropertiesloaderTest.cs
.
예, 내가 알고있는 수업이 내장되어 있지 않습니다.
그러나 그것은 실제로 문제가되어서는 안됩니까? 결과를 저장하는 것만으로 구문 분석하기에 충분히 쉬워 보입니다. Stream.ReadToEnd()
문자열에서 새 라인을 기반으로 분할 한 다음 각 레코드를 =
캐릭터. 당신이 남겨 두는 것은 사전에 쉽게 던질 수있는 키 값 쌍입니다.
다음은 귀하에게 효과가있는 예입니다.
public static Dictionary<string, string> GetProperties(string path)
{
string fileData = "";
using (StreamReader sr = new StreamReader(path))
{
fileData = sr.ReadToEnd().Replace("\r", "");
}
Dictionary<string, string> Properties = new Dictionary<string, string>();
string[] kvp;
string[] records = fileData.Split("\n".ToCharArray());
foreach (string record in records)
{
kvp = record.Split("=".ToCharArray());
Properties.Add(kvp[0], kvp[1]);
}
return Properties;
}
다음은 사용 방법의 예입니다.
Dictionary<string,string> Properties = GetProperties("data.txt");
Console.WriteLine("Hello: " + Properties["Hello"]);
Console.ReadKey();
실제 대답이 없(적어도 자).할 수 있습니다 여전히 자신의 코드 그것을 할 수 있습니다.
C#은 일반적으로 *.ini 스타일 파일 대신 XML 기반 구성 파일을 사용하므로이를 처리 할 내장은 없습니다. 그러나 Google은 반환합니다 유망한 결과의 수.
나는 이것을하는 내장 방법을 모른다. 그러나 당신이 걱정해야 할 유일한 구분자는 Newline 캐릭터와 동등한 신호이기 때문에 충분히 쉬운 것처럼 보일 것입니다.
NameValueCollection 또는 파일의 내용이 주어지면 우려를 반환하는 루틴을 작성하는 것은 매우 쉽습니다.
기본값 및 제한 세트와 함께 C# 자동 속성 구문을 사용할 수도 있습니다. 여기서 장점은 속성 "파일"(실제로 클래스)에 모든 종류의 데이터 유형을 가질 수 있다는 것입니다. 다른 장점은 C# 속성 구문을 사용하여 속성을 호출 할 수 있다는 것입니다. 그러나이 작업을 수행하려면 각 속성 (재산 선언에 1 개, 생성자에 1 개)에 대해 몇 줄만 필요합니다.
using System;
namespace ReportTester {
class TestProperties
{
internal String ReportServerUrl { get; private set; }
internal TestProperties()
{
ReportServerUrl = "http://myhost/ReportServer/ReportExecution2005.asmx?wsdl";
}
}
}
이를위한 몇 가지 NUGET 패키지가 있지만 현재 모두 프리 릴리스 버전에 있습니다.
- capgemini.cauldron.core.javaproperties 2.0.39- 베타
- kajabity.tools.java 0.2.6638.28124
업데이트] 2018 년 6 월 현재, capgemini.cauldron.core.javaproperties 이제 안정적인 버전 (버전 2.1.0 및 3.0.20)입니다.
나이지 않을 정확히 무엇을 요구하고 있지만,단지의 경우:
하려는 경우드 제 Java properties 파일에,당신은 필요 위치의 인코딩이 있습니다. Java 문서 을 나타내는 인코딩은 ISO8859-1 포함하는 일부 탈출 시퀀스할 수 있는지 제대로 해석할 수 있습니다.예를 들어 봐 이렇게 대답 무엇을 볼 수를 설정하는 데 필요 UTF-8ISO8859-1(그리고 반대로)
우리가 필요로 할 때 이를 위해,우리가 발견한 오픈 소스 PropertyFile.cs 고 몇 가지 변화를 만들어 지원합니다.이 클래스입니다 읽기/쓰기 시나리오.해야 합 지원 PropertyFileIterator.cs 뿐만 아니라 클래스.
하지 않은 경우에도로드 진 Java 속성을 확인하는 귀하의 소품이 파일을 표현할 수 있는 모든 캐릭터를 저장해야 합(UTF-8 이상)
가 정확한 솔루션 당신이 무엇을 원합니다.을 찾을하시기 바랍에서 문서 기
그의 코드의 무리에 있는 강한 포인트에 대한 효율성이다.
- 응용 프로그램을 로드하지 않는 텍스트 파일에 모든 요청을 합니다.그 을 로드하는 텍스트 파일만 한 번에 메모리입니다.에 대한 후속 요청,그것은 값을 반환합에서 직접 메모리입니다.이것은 많 더 효율적으로는 경우 텍스트 파일로 수천을 포함하나 이상 키-값 쌍으로 이루어져 있습니다.
- 어떤 변경 텍스트 파일에서 필요로하지 않는 응용 프로그램 다시 시작합니다.A 파일 시스템을 감시자는 사용을 추적하는 파일의 상태에 있습니다.을 변경하는 경우,그것은 이벤트가 트리거와 로드하는 새로운 변화 에 따라 메모리도록 변경할 수 있습니다에서 텍스트 파일 중 하나 응용 프로그램/텍스트 편집기조 변화에 효과 웹사 응용 프로그램.
- 당신은 단지 그것을 사용할 수 있 웹 응용 프로그램에서도 수 에서 사용하는 모든 데스크톱 응용 프로그램입니다.
감사합니다.Have a nice day.
아니요.
public class PropertiesUtility
{
private static Hashtable ht = new Hashtable();
public void loadProperties(string path)
{
string[] lines = System.IO.File.ReadAllLines(path);
bool readFlag = false;
foreach (string line in lines)
{
string text = Regex.Replace(line, @"\s+", "");
readFlag = checkSyntax(text);
if (readFlag)
{
string[] splitText = text.Split('=');
ht.Add(splitText[0].ToLower(), splitText[1]);
}
}
}
private bool checkSyntax(string line)
{
if (String.IsNullOrEmpty(line) || line[0].Equals('['))
{
return false;
}
if (line.Contains("=") && !String.IsNullOrEmpty(line.Split('=')[0]) && !String.IsNullOrEmpty(line.Split('=')[1]))
{
return true;
}
else
{
throw new Exception("Can not Parse Properties file please verify the syntax");
}
}
public string getProperty(string key)
{
if (ht.Contains(key))
{
return ht[key].ToString();
}
else
{
throw new Exception("Property:" + key + "Does not exist");
}
}
}
도움이 되었기를 바랍니다.