星期五, 十二月 29, 2006

[JAVA]数据读取DataInputStream.readLine()的替换方式

根据jdk上说的,DataInputStream.readLine()这个方法已经被舍弃不用了
原因是它不能很好的完成bytes到charaters的转换,所以方法替换如下
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
然后用 reader.readLine() 来读取文件里的一行

星期四, 十月 12, 2006

[JAVA]将ISO-8859-1编码转换为GBK编码

public String translate(String str)
{
String tempStr = "";
try
{
tempStr = new String(str.getBytes("ISO-8859-1"), "GBK");
tempStr = tempStr.trim();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
return tempStr;
}

星期三, 十月 11, 2006

[C#]将普通字符串转换为Base64编码字符串

// 将字符串转换为Base64编码
Byte[] buf = System.Text.ASCIIEncoding.UTF8.GetBytes(sourceString);
String resultString = Convert.ToBase64String(buf, 0, buf.Length);


// 从Base64编码转换回一般字符串
Byte[] bufout = Convert.FromBase64String(EncryptedString);
String resultString = System.Text.ASCIIEncoding.UTF8.GetString(bufout);

星期四, 九月 14, 2006

(VC++)VC使用MSXML解析XML文档,例子代码

现在XML文档应用的方面特别的多.
我把以前写过的一个例子帖出来,以备以后使用.
第一部分:DOM解析:
概述:DOM解析将会把一个完整的XML文档读进来,生成一个结构树。这样会要把XML文档全部都加载到内在中。所以解析起来的速度会要慢一些。

1、如何加载xml文件:

//创建DOM,加载XML文档
MSXML::IXMLDOMDocumentPtr pCommandDoc;
pCommandDoc.CreateInstance(__uuidof(MSXML::DOMDocument));
pCommandDoc->put_async(VARIANT_FALSE);
pCommandDoc->put_validateOnParse(VARIANT_FALSE);
pCommandDoc->put_resolveExternals(VARIANT_FALSE);
pCommandDoc->put_preserveWhiteSpace(VARIANT_TRUE);
pCommandDoc->load(file.GetBuffer(0));

2、在XML文档中查找指定的结点:

//找到
MSXML::IXMLDOMNodePtr pRootNode=pCommandDoc->selectSingleNode("root/record");
if (pRootNode==NULL)
{
return ;
}

3、得到XML文档中,结点的属性

CString strTemp;
MSXML::IXMLDOMNamedNodeMapPtr pAttrs = NULL;
pRootNode->get_attributes(&pAttrs);
if (pAttrs==NULL)
{
return;
}
MSXML::IXMLDOMNodePtr pRequestTypeAttr=pAttrs->getQualifiedItem("name","");
_bstr_t strRequestType=pRequestTypeAttr->Gettext();
strTemp=strRequestType.operator char *();

4、得到结点的内容

_bstr_t strVisiPort=pNode->Gettext();

5、设置结点的内容

HRESULT hr=pNode->put_text(_bstr_t(m_strGatewayPassword));


6、设置一个属性内容
IXMLDOMAttribute *pa=NULL;
bstr = SysAllocString(L"属性1");
pXMLDom->createAttribute(bstr,&pNode);
var = VariantString(L"strin");
pa->put_value(var);
pRoot->setAttributeNode(pa, &pa1);


第二部分、如何使用SAX解析

概述:SAX使用的是加载式的,将会把XML文档分断,加载到内存中。使用事件通知的方式,来表示找到结点。好像没有写文档的能力吧。它的速度要比DOM快不少。

使用SAX的时候,就需要重载MSXML4.0中的一个接口ISAXContentHandler。

有几个函数重载了之后,当找到了结点之后,就会回调这一些函数。

(VB.NET)使用性能计数器

Imports System

Imports System.Management

Module Module1

Public Sub Main()


Dim strComputer As String = "." , i, intValue As Integer

Dim colItems, objWMIService, objItem


objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")


For i = 1 To 5

Threading.Thread.Sleep(1000)

colItems = objWMIService.ExecQuery("Select * From Win32_PerfRawData_PerfProc_Process Where Name = 'devenv'" )

For Each objItem In colItems

intValue = objItem.HandleCount

Console.WriteLine("打开的句柄数 :" & intValue)

Next

Next
End Sub
End Module

使用Getobject
函数创建对象多用于脚本中,所以参数为WMI 脚本库的标记名 "winmgmts:" 和目标电脑名,上述的strComputer="." 相当于localhost ,若在远程计算机上执行则需将 "." 改这相应的计算机名。

其中:

ManagementObject:单个管理对象

ManagementClass:单个管理类

ManagementObjectSearcher:查询 管理对象及管理的集合

ManagementEventWatcher:监视来自 WMI 的事件

ManagementQuery:用作所有查询类的基础。


也可以从脚本中创建:

Set oLocator = CreateObject("WbemScripting.SWbemLocator") ' New SWbemLocator
If Err.Number <> 0 Then
MsgBox "Windows Management (WMI)
不能被创建" & Err.Description
WScript.Quit(0)
End If

----------------------------------------------------------------------
set locator = createobject(" WbemScripting.SwbemLocator")
set server = locator.ConnectServer ("\\192.168.0.1\root\cimv2","username","password")
set p_obj = server.execquery("select * form Win32_operatingsystem")

for each p_objswbem in p_obj
p_objswbem.reboot '
从新启动

next


WMI 的有关概述请参考 MSDN http://www.csdn.net/develop/Article/19/19157.shtm


(VB.NET)删除日志文件:(请先备份)

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim strComputer = "."

Dim objWMIService, objLogFiles, objLogFile, logs, mylogs( 3)

objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Backup)}!\\" & strComputer & "\root\cimv2")

mylogs(1) = "application"

mylogs(2) = "system"

mylogs(3) = "security"

For Each logs In mylogs

objLogFiles = objWMIService.ExecQuery("Select * from Win32_NTEventLogFile where LogFileName='" & logs & "'")

For Each objLogFile In objLogFiles

objLogFile.ClearEventLog()

Next

Next

End Sub

End Module

(VB.NET)读取日志记录

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim strComputer = "magicdog"

Dim wbemServices, wbemObjectSet, wbemObject

wbemServices = GetObject("winmgmts:\\" & strComputer)

wbemObjectSet = wbemServices.InstancesOf("Win32_NTLogEvent")

For Each wbemObject In wbemObjectSet

Console.WriteLine("日志文件:" & wbemObject.LogFile)

Console.WriteLine("记录号:" & wbemObject.RecordNumber)

Console.WriteLine("类型:" & wbemObject.Type)

Console.WriteLine("产生时间:" & wbemObject.TimeGenerated)

Console.WriteLine("源名称:" & wbemObject.SourceName)

Console.WriteLine("事件代码:" & wbemObject.EventCode)

Console.WriteLine("用户" & wbemObject.User)

Console.WriteLine("计算机名:" & wbemObject.ComputerName)

Console.WriteLine("信息:" & wbemObject.Message)

Next

End Sub

End Module

(VB.NET)获取物理内存大小

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim strComputer = "ComputerName" '计算机名

Dim wbemServices, wbemObjectSet, wbemObject

wbemServices = GetObject("winmgmts:\\" & strComputer)

wbemObjectSet = wbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")

For Each wbemObject In wbemObjectSet

Console.WriteLine("物理内存的大小 (kb):" & wbemObject.TotalPhysicalMemory)

Next

End Sub

End Module

(VB.NET)获取远程机器的目录以及文件信息

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim disk As ManagementObject = New ManagementObject( "win32_logicaldisk.deviceid=""c:""")

disk.Get()

Console.WriteLine("硬盘容量大小(bytes): " & disk("Size"))

End Sub

End Module

(VB.NET)获取可用内存大小

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim strComputer As String = "." , i, intValue As Integer

Dim colItems, objWMIService, objItem

objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'重复执行 20 次检查

For i = 1 To 20

'产生内存快照

colItems = objWMIService.ExecQuery("Select * From Win32_PerfRawData_PerfOS_Memory")

For Each objItem In colItems

intValue = objItem.AvailableMbytes

Console.WriteLine("可用内存大小 (MB): " & intValue )

'延时 5 秒

Threading.Thread.Sleep(5000)

Next

Next

End Sub

End Module

(VB.NET)获取服务名

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim strComputer = "ComputerName"

Dim wbemServices, wbemObjectSet, wbemObject

wbemServices = GetObject("winmgmts:\\" & strComputer)

wbemObjectSet = wbemServices.InstancesOf("Win32_Service")

For Each wbemObject In wbemObjectSet

Console.WriteLine("服务名称:" & wbemObject.DisplayName)

Console.WriteLine("当前状态:" & wbemObject.State)

Console.WriteLine("启动模式:" & wbemObject.StartMode)

Next

End Sub

End Module

(VB.NET)从新启动远程计算机:(需要权限)

Imports System

Imports System.Management

Module Module1

Public Sub Main()

Dim co As ConnectionOptions = New ConnectionOptions

co.Username = "Admin" '登录的用户名称

co.Password = "12345678" 'Password

Dim ms As System.Management.ManagementScope = New System.Management.ManagementScope ("\\192.168.1.2\root\cimv2", co)

Dim oq As System.Management.ObjectQuery = New System.Management.ObjectQuery ("SELECT * FROM Win32_OperatingSystem")

Dim mos As ManagementObjectSearcher = New ManagementObjectSearcher(ms, oq)

Dim _query As ManagementObjectCollection = mos.Get()

Dim mo As ManagementObject

For Each mo In _query

Dim tmp() As String = {"" }

mo.InvokeMethod("Reboot", tmp)

Console.WriteLine(mo.ToString())

Next

End Sub

End Module

(VB.NET)Windows Management Instrumentation

WMI,是基于 Web Based Enterprise Management WBEM)的面向对象数据库, 一个管理企业环境开发 的标准接口。可以利用它访问本地主机的一些信息和服务、监视计算机、管理远程计算机

VS.NET 中需要添加引用:System.Management.dll, 这样你的项目才能使用WMI

WMI 的使用灵活,但 class 也多,如: CPU 的系列号-Win32_Processor 、主板BIOS 的系列号-Win32_BIOS 、本地磁盘-Win32_LogicalDisk共享资源- Win32_share等等,详细的 WMI 类名可以在MSDN 中查询 ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/wmisdk/wmi/win32_classes.htm

也可以使用WMI Tools 管理WMI 服务的名称空间 http://www.microsoft.com/downloads/details.aspx?FamilyId=6430F853-1120-48DB-8CC5-F2ABDC3ED314&displaylang=en

用这个程序也可以获取WMI Class Name

------------------------------------------------------------------------------------

Dim WMI As Management.ManagementClass

Dim info As Management.ManagementObject

' 返回 WMI 的 Class Name 到 String Array

Private Function FindWMI(ByVal IndexString As String, ByVal Deep As Boolean) As String()

Try

Dim _WMIList() As String

WMI = New Management.ManagementClass

Dim options As New Management.EnumerationOptions

Dim chClass As String = Nothing

If Not IndexString Is Nothing Then

chClass = IndexString

End If

options.EnumerateDeep = Deep

For Each info In WMI.GetSubclasses(options)

If _WMIList Is Nothing Then

ReDim _WMIList(0)

Else

ReDim Preserve _WMIList(UBound(_WMIList) + 1)

End If

If chClass Is Nothing Then

_WMIList(UBound(_WMIList)) = (info.Item("__Class"))

Else

If info.Item("__Class").ToString.Substring(0, _

IIf(info.Item("__Class").ToString.Length > chClass.Length, _

chClass.Length, info.Item("__Class").ToString.Length)).ToLower = chClass Then

_WMIList(UBound(_WMIList)) = (info.Item("__Class"))

End If

End If

Application.DoEvents()

Next

options = Nothing

info = Nothing

WMI = Nothing

Return _WMIList

Catch ex As Exception

MsgBox(ex.Message, 16 + 0, ex.TargetSite.Name)

End Try

End Function

' 获取 WMI 的 Class Info 并将其写入输出窗口

Private Sub GetInfo(ByVal IndexString As String)

Try

If IndexString Is Nothing Then Exit Sub

Dim wmiClass As String = IndexString

WMI = New Management.ManagementClass(wmiClass)

Dim strInfo As String

Console.WriteLine("WMI Class is:" & wmiClass)

For Each info In WMI.GetInstances

' WMI Class Info 写到输出窗口

Console.WriteLine(info.GetText(Management.TextFormat.Mof).ToString)

Next

info = Nothing

WMI = Nothing

Catch ex As Exception

MsgBox(ex.Message, 16 + 0, ex.TargetSite.Name)

End Try

End Sub

------------------------------------------------------------------------------------

使用时:

Dim tmpStr() As String, i As Integer

'获取 WMI 的 Class Name

tmpStr = FindWMI(Nothing, True)

'列出 Class Name Array 中的第 559 个 Class 的 Info

GetInfo(tmpStr(559))

'列出物理内存的信息

GetInfo("Win32_PhysicalMemory")