summaryrefslogtreecommitdiff
path: root/src/test
diff options
context:
space:
mode:
authorchenjinsong <[email protected]>2018-09-27 16:11:54 +0800
committerchenjinsong <[email protected]>2018-09-27 16:11:54 +0800
commit56d71f261a8bd6031e47e2bf80867049a2aa13da (patch)
treef09257b2143782a333a9eda3395137837d9bdad1 /src/test
initial commit
Diffstat (limited to 'src/test')
-rw-r--r--src/test/HotSwapCL.java73
-rw-r--r--src/test/Test.java182
-rw-r--r--src/test/Test1.java342
-rw-r--r--src/test/TestNet.java151
4 files changed, 748 insertions, 0 deletions
diff --git a/src/test/HotSwapCL.java b/src/test/HotSwapCL.java
new file mode 100644
index 0000000..488e27a
--- /dev/null
+++ b/src/test/HotSwapCL.java
@@ -0,0 +1,73 @@
+package test;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashSet;
+import org.apache.log4j.Logger;
+
+import com.nis.nmsclient.util.Utils;
+
+class HotSwapCL extends ClassLoader {
+ private Logger logger = Logger.getLogger(ClassLoader.class);
+ private String basedir; // 需要该类加载器直接加载的类文件的基目录
+ private HashSet dynaclazns; // 需要由该类加载器直接加载的类名
+
+ public HotSwapCL(String basedir, String[] clazns) {
+ super(null); // 指定父类加载器为 null
+ this.basedir = basedir;
+ dynaclazns = new HashSet();
+ loadClassByMe(clazns);
+ }
+
+ private void loadClassByMe(String[] clazns) {
+ for (int i = 0; i < clazns.length; i++) {
+ try {
+ loadDirectly(clazns[i]);
+ } catch (Exception e) {
+ logger.error(Utils.printExceptionStack(e));
+ }
+ dynaclazns.add(clazns[i]);
+ }
+ }
+
+ private Class loadDirectly(String name) throws Exception{
+ Class cls = null;
+ StringBuffer sb = new StringBuffer(basedir);
+ String classname = name.replace('.', File.separatorChar) + ".class";
+ sb.append(File.separator + classname);
+
+ File classF = new File(sb.toString());
+ cls = instantiateClass(name, new FileInputStream(classF), classF
+ .length());
+ return cls;
+ }
+
+ private Class instantiateClass(String name, InputStream fin, long len) throws Exception{
+ byte[] raw = new byte[(int) len];
+ try {
+ fin.read(raw);
+ } catch (IOException e) {
+ throw e;
+ }finally{
+ if(fin!=null){
+ fin.close();
+ }
+ }
+ return defineClass(name, raw, 0, raw.length);
+ }
+
+ protected Class loadClass(String name, boolean resolve)
+ throws ClassNotFoundException {
+ Class cls = null;
+ cls = findLoadedClass(name);
+ if (!this.dynaclazns.contains(name) && cls == null)
+ cls = getSystemClassLoader().loadClass(name);
+ if (cls == null)
+ throw new ClassNotFoundException(name);
+ if (resolve)
+ resolveClass(cls);
+ return cls;
+ }
+}
diff --git a/src/test/Test.java b/src/test/Test.java
new file mode 100644
index 0000000..9100a94
--- /dev/null
+++ b/src/test/Test.java
@@ -0,0 +1,182 @@
+package test;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.nis.nmsclient.common.Contants;
+import com.nis.nmsclient.util.DateUtil;
+import com.nis.nmsclient.util.FileUtil;
+import com.nis.nmsclient.util.FileWrUtil;
+
+public class Test {
+ public static void main(String[] args) {
+ //method2();
+ //method1();
+
+ /*File file = new File("C:\\Documents and Settings\\zhenzhen\\桌面\\nmsdata\\test1");
+ long now = System.currentTimeMillis();
+
+ File[] files = file.listFiles();
+ for(File file2 : files){
+ System.out.println("========"+file2.getName());
+ }
+ System.out.println(System.currentTimeMillis()-now);
+
+ now = System.currentTimeMillis();
+
+ String[] fileNames = file.list();
+ for(String file2 : fileNames){
+ System.out.println("========"+file2);
+ }
+ System.out.println(System.currentTimeMillis()-now);*/
+ /*try {
+ long now = System.currentTimeMillis();
+ ProcessUtil.getProcessId("javaw.exe");
+ System.out.println(System.currentTimeMillis()-now);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }*/
+
+ /*try {
+ FileUtils.copyDirectoryToDirectory(new File("D:\\temp\\test"), new File("D:\\temp\\t1"));
+ FileUtils.copyDirectory(new File("D:\\temp\\test"), new File("D:\\temp\\test2"));
+ File file = new File("D:\\temp\\tt\\temp");
+ if(file.getParentFile().canWrite()){
+ System.out.println("Yes");
+ }
+ String[] except = new String[3];
+ except[0]="D:\\temp\\test\\WebRoot";
+ except[1]="D:\\temp\\test\\t1.tar.gz";
+ except[2]="D:\\temp\\test\\src\\filemgr\\ZipUtil.java";
+ //new AgentCommand().backup(new File("D:\\temp\\test"), new File("D:\\temp\\t2"), except);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }*/
+ /*String filepath = "";
+ if(filepath.startsWith("/") || (filepath.length()>3 && filepath.substring(1,3).equals(":\\"))){
+ System.out.println("ff");
+ }*/
+ /*File file = new File("D:\\temp");
+ File file2 = new File("D:\\temp\\test\\..");
+ System.out.println(file.compareTo(file2));
+ try{
+ System.out.println(file.getCanonicalPath() + "--" + file2.getCanonicalPath());
+ }catch (Exception e) {
+ // TODO: handle exception
+ }*/
+ try {
+ //ProcessUtil.runExec("D:/test.bat");
+ /*ProcessUtil.runExec("D:\\Program Files\\PLSQL Developer\\plsqldev.exe");
+ String cmd ="D:/Program Files/Navicat for MySQL/navicat.exe";
+ Runtime.getRuntime().exec("cmd /c " + cmd.replace(" ", "\" \""));
+ //ProcessUtil.runExec("D:/Program Files/feiq/飞秋FeiQ.exe");
+ String tempString = "0";
+ int length = tempString.split(":").length;
+ System.out.println(length);*/
+
+ /*Properties prop = System.getProperties();
+ for(Map.Entry<Object,Object> entry : prop.entrySet()){
+ System.out.println(entry.getKey()+"="+entry.getValue());
+ }*/
+
+ System.out.println(Contants.class.getClassLoader().getResource("myconfig.properties").getPath()) ;
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ public static void method1(){
+ long curDate = System.currentTimeMillis();
+
+ // 删除指定分钟之前的所有监测文件
+ File file = new File("C:/Documents and Settings/zhenzhen/桌面/nmsdata/test");
+ if (!file.exists()) {
+ return;
+ }
+ File[] dirs = FileUtil.getDirectoryArray(file);
+ if (dirs == null || dirs.length <= 0) {
+ return;
+ }
+ for (File dir : dirs) {
+ File[] files = FileUtil.getFilesEndWith(dir, ".csv");
+ if (files == null || files.length <= 0) {
+ return;
+ }
+ for (File f : files) {
+ long diff = DateUtil.getMinutesFromBeginToEnd(f.lastModified(), curDate);
+
+ if (f.exists() && diff > 1) {
+ f.delete();
+ }
+ }
+ }
+
+ System.out.println("=========method1 : " + (System.currentTimeMillis()-curDate));
+ }
+
+ public static void method2(){
+ try {
+ long curDate = System.currentTimeMillis();
+
+ List<String> arrayList = new ArrayList<String>();
+
+ // 删除指定分钟之前的所有监测文件
+ File file = new File("D:/test1");
+ if (!file.exists()) {
+ return;
+ }
+ File[] dirs = FileUtil.getDirectoryArray(file);
+ if (dirs == null || dirs.length <= 0) {
+ return;
+ }
+ for (File dir : dirs) {
+ File[] files = FileUtil.getFilesEndWith(dir, ".csv");
+ if (files == null || files.length <= 0) {
+ return;
+ }
+ for (File f : files) {
+ //arrayList.add(f.getAbsolutePath());
+ FileWrUtil.cfgFileAppender(new File("C:/Documents and Settings/zhenzhen/桌面/nmsdata/test.txt"), "utf-8", new String[]{f.getAbsolutePath()});
+ }
+ }
+
+ //String[] tmp = new String[arrayList.size()];
+ //FileWrUtil.cfgFileAppender(new File("C:/Documents and Settings/zhenzhen/桌面/nmsdata/test.txt"), "utf-8", arrayList.toArray(tmp));
+
+ System.out.println("=========method2 Write end : " + (System.currentTimeMillis()-curDate));
+
+ curDate = System.currentTimeMillis();
+
+ FileInputStream in = new FileInputStream(new File("C:/Documents and Settings/zhenzhen/桌面/nmsdata/test.txt"));
+ BufferedReader bReader = new BufferedReader(new InputStreamReader(in, Contants.charset));
+ String line = "";
+ List<File> arrList = new ArrayList<File>();
+ while ((line = bReader.readLine()) != null){
+ /*File file2 = new File(line);
+ if(file2.exists()){
+ file2.delete();
+ }*/
+ arrList.add(new File(line));
+ }
+ bReader.close();
+ in.close();
+ System.out.println("=========method2 : " + (System.currentTimeMillis()-curDate));
+ curDate = System.currentTimeMillis();
+ for(File file3 : arrList){
+ if(file3.exists()){
+ file3.delete();
+ }
+ }
+
+ System.out.println("=========method2 : " + (System.currentTimeMillis()-curDate));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/src/test/Test1.java b/src/test/Test1.java
new file mode 100644
index 0000000..9b38f03
--- /dev/null
+++ b/src/test/Test1.java
@@ -0,0 +1,342 @@
+package test;
+
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+import com.nis.nmsclient.common.Common;
+
+
+public class Test1 {
+
+ private Thread singleThread;
+ public void testThread(){
+ int i = 0;
+ final long loopDelay = 1l;
+ final long delay = 0;
+ ScheduledFuture<?> taskFuture = null;
+ final String threadName = "测试线程";
+ taskFuture = Common.scheduled.schedule(new Runnable() {
+ public void run() {
+ synchronized (singleThread) {
+ singleThread = Thread.currentThread();
+ }
+ Thread.currentThread().setName(threadName + " 周期单次");
+ System.out.println("new AgentCommand(command).exec();");
+ }
+ }, 0, TimeUnit.MILLISECONDS);
+ ThreadNN tt = new ThreadNN(taskFuture, threadName, singleThread);
+ taskFuture = Common.scheduled.scheduleAtFixedRate(
+ tt, delay, 6 * 1000, TimeUnit.MILLISECONDS);
+ try {
+ Thread.sleep(10*1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ //if(i>1){
+ tt.cancle();
+ System.out.println(i+";taskFuture.isCancelled():"+taskFuture.isCancelled());
+ System.out.println(i+";taskFuture.isDone():"+taskFuture.isDone());
+ System.out.println(i+";taskFuture.cancel(true):"+taskFuture.cancel(true));
+ System.out.println(i+";taskFuture.cancel(true):"+taskFuture.cancel(false));
+ System.out.println(i+";taskFuture.isCancelled():"+taskFuture.isCancelled());
+ System.out.println(i+";taskFuture.isDone():"+taskFuture.isDone());
+ //System.out.println(i+";runnable.stop()before;runnable.getState():"+runnable.getState());
+ //runnable.notify();
+
+ //runnable.destroy();
+ //runnable.stop();
+
+ //System.out.println(i+";runnable.stop();runnable.getState():"+runnable.getState());
+ //System.out.println(i+";runnable.stop();runnable.getState():"+runnable.getState());
+ //System.out.println(i+";runnable.stop();taskFuture.isCancelled():"+taskFuture.isCancelled());
+ System.out.println(i+";runnable.stop();taskFuture.isDone():"+taskFuture.isDone());
+ //taskFuture = null;
+ //StringUtils.isNotEmpty(new StringBuilder());
+
+ //}
+ }
+ public static void main(String args[]){
+ Test1 t = new Test1();
+ t.testThread();
+ }
+
+ static class ThreadNN extends Thread{
+ private ScheduledFuture<?> singleFuture;
+ private String threadName;
+ private ScheduledFuture<?> lastFuture = null;
+ private long i = 0;
+ private Thread thread;
+ private Thread singleThread;
+
+ public ThreadNN(ScheduledFuture<?> singleFuture, String threadName, Thread singleThread){
+ this.singleFuture = singleFuture;
+ this.threadName = threadName;
+ this.singleThread = singleThread;
+ }
+
+ public synchronized void cancle() {
+ if(thread!=null && thread.isAlive()){
+ System.out.println("------thread.isAlive()------" + thread.isAlive());
+ thread.stop();
+ System.out.println("------thread.isAlive()------" + thread.isAlive());
+ }
+ }
+
+ public void run() {
+ i++;
+ Thread.currentThread().setName(threadName + " 周期" + i);
+ System.out.println(i+"--start====="+this.getState());
+ long et = System.currentTimeMillis();// 本次开始时间,即上次执行结束时间
+ long st = et;// - (i * loopDelay * 60 * 1000);// 上次开始时间
+ try {
+ if (i == 1 && singleFuture != null
+ && !singleFuture.isCancelled()
+ && !singleFuture.isDone()) {
+ synchronized (singleThread) {
+ if(singleThread!=null){
+ singleThread.stop();
+ System.out.println("singleThread Timeout stop thread--" + thread.isAlive());
+ singleThread = null;
+ }
+ }
+ singleFuture.cancel(true);
+ }
+ if (lastFuture != null
+ && !lastFuture.isCancelled()
+ && !lastFuture.isDone() && thread!=null) {
+ thread.stop();
+ System.out.println(i+"--LoopTaskThread run Timeout stop thread--" + thread.isAlive());
+ lastFuture.cancel(true);
+ lastFuture = null;
+ thread = null;
+ System.out.println(i+"--TaskResultOper.sendTaskResult(command.getExecId(),command.getExecType(),AgentCommand.RESULT_FAIL,本周期任务执行超时, , new Date(st),new Date(et), command.getIsLoop());");
+ }
+ lastFuture = Common.scheduled.schedule(new Runnable() {
+ public void run() {
+ thread = Thread.currentThread();
+ Thread.currentThread().setName(threadName + " 周期" + i);
+ System.out.println(i+"---新周期的执行new AgentCommand(command).exec()");
+
+ for(long j=0l;j<=2000000000; j++){
+ if(j==0 || j==100 || j==1000 || j==10000 || j==100000 || j==1000000 || j==2000000000){
+ System.out.println(i+"--------"+j);
+ }
+ }
+ }
+ }, 0, TimeUnit.MILLISECONDS);
+ System.out.println(i+"--end====="+this.getState());
+ //lastFuture.get();
+ System.out.println(i+"--last====="+this.getState());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+ /**
+ * 回传文件:先将信息写入临时文件,再判断与Server端通信是否成功
+ * 1、通信成功:回传所有文件,发送最终结果;删除临时文件
+ * 2、通信失败:保留临时文件,直接返回
+ * @param rfPo 回传文件实体类
+ */
+// public void sendTaskReturnFile(ReturnFilePO rfPo) {
+// if(rfPo==null || rfPo.getFilePathMap()==null || rfPo.getFilePathMap().size()<=0){
+// logger.warn("无回传文件, 不用回传");
+// return;
+// }
+// File tempDir = null;
+// try {
+// /**
+// * 步骤1、将信息写入文件
+// */
+// final File file = new File(getTaskReturnFile(rfPo.getTaskType(),
+// rfPo.getTaskId()));
+// if (!file.exists()) {
+// String[] values = new String[] { JSONObject.fromObject(
+// rfPo).toString() };
+// FileWrUtil.cfgFilePrinter(file, Contants.charset,
+// values);
+// }
+// /**
+// * 步骤2、与Server通信
+// */
+// Future<?> serFuture = ThreadPool.service.submit(new SSLClient(
+// Thread.currentThread().getName(),
+// CommonSocket.REQ_HAND_SHAKE, null));
+// if (!SSLClient.isSucessByResult((String) serFuture.get())) {
+// return;
+// }
+// /**
+// * 步骤3、回传文件
+// */
+// StringBuffer sb = new StringBuffer();
+// if(rfPo.getResDesc()!=null){//取已有的结果描述信息
+// sb.append(rfPo.getResDesc());
+// }
+// if(rfPo.getFilePathMap()!=null && rfPo.getFilePathMap().size()>0){
+// tempDir = new File(Contants.localTempPath + File.separator
+// + "return_" + rfPo.getTaskId());
+// if(!tempDir.exists()){
+// tempDir.mkdirs();
+// }
+// /**
+// * 步骤3-1 处理回传文件:1、过滤不存在或文件路径为空的文件 2、处理文件别名并对文件夹压缩,或对文件重命名
+// */
+// Set<Map.Entry<String, String>> entrySet = rfPo.getFilePathMap().entrySet();
+// for(Map.Entry<String, String> entry : entrySet){
+// String returnPath = entry.getKey();
+// String aliasName = entry.getValue();
+// if (StringUtils.isEmpty(returnPath)) {
+// sb.append("回传“" + returnPath + "”失败,回传文件路径值为空;");
+// rfPo.getFilePathMap().remove(returnPath);
+// continue;
+// }
+// File returnFile = new File(returnPath);
+// if (!returnFile.exists()) {
+// sb.append("回传“" + returnPath + "”失败,回传文件不存在;");
+// rfPo.getFilePathMap().remove(returnPath);
+// continue;
+// }
+// //回传文件取别名,用于Server端断点续传
+// if(aliasName==null || aliasName.length()<=0){
+// aliasName = CommonSocket.addTimeTagForFileName(
+// returnFile.getName(), rfPo.getTaskId());
+// if(returnFile.isDirectory()){
+// aliasName += CompressFileMgr.getCompressSuffixByOs(false);
+// }
+// rfPo.getFilePathMap().put(returnPath, aliasName);
+// }
+// // 文件夹的话压缩,文件直接回传
+// File returnTmpFile = new File(tempDir.getCanonicalPath()
+// + File.separator
+// + aliasName);
+// if(!returnTmpFile.exists()){
+// if (returnFile.isDirectory()) {
+// new CompressFileMgr().compressFile(returnFile
+// .getAbsolutePath(), returnTmpFile
+// .getAbsolutePath(), null, false);
+// } else {
+// FileUtils.copyFile(returnFile, returnTmpFile);
+// }
+// }
+// }
+//
+// /**
+// * 步骤3-2 将处理后的回传文件信息重新写入文件
+// */
+// rfPo.setResDesc(sb.toString());
+// String[] values = new String[] { JSONObject.fromObject(
+// rfPo).toString() };
+// FileWrUtil.cfgFilePrinter(file, Contants.charset,
+// values);
+//
+// /**
+// * 步骤3-3 开始回传文件
+// */
+// entrySet = rfPo.getFilePathMap().entrySet();
+// List<String> successKeys = new ArrayList<String>();
+// for(Map.Entry<String, String> entry : entrySet){
+// String key = entry.getKey();
+// File returnFile = new File(tempDir.getCanonicalPath()
+// + File.separator
+// + entry.getValue());
+// rfPo.setCurRetrunFile(returnFile);
+//
+// for(int i=0; i<Contants.max_times; i++){//回传失败,尝试几次
+// Future<?> future = ThreadPool.service.submit(new SSLClient(
+// Thread.currentThread().getName(),
+// CommonSocket.REQ_TASK_RETURNFILE, rfPo));
+// String msg = (String) future.get();
+// if(SSLClient.isSucessByResult(msg)){
+// sb.append("回传“" + key + "”成功;");
+// successKeys.add(key);
+// break;
+// }
+//
+// try {// 如果更新失败,让当前线程暂停几秒,再重试
+// Thread.sleep(1000 * Contants.max_delay_seconds);
+// } catch (InterruptedException e) {
+// logger.error(Utils.printExceptionStack(e));
+// continue;
+// }
+// }
+// //sb.append("回传“" + returnPath + "”" + (resultDesc==null ? "失败" : resultDesc) + ";");
+// }// for end
+// for(String key : successKeys){
+// rfPo.getFilePathMap().remove(key);
+// }
+// }
+//
+// /**
+// * 步骤4、判断文件是否全部回传完成
+// */
+// if(rfPo.getFilePathMap().size()==0){
+// /**
+// * 步骤4-1、发送任务结果
+// */
+// TaskResultOper.sendTaskResult(rfPo.getTaskId(), rfPo.getTaskType(),
+// rfPo.getState(), sb.toString(), "", rfPo.getStartTime(),
+// rfPo.getEndTime(), rfPo.getIsLoop());
+// /**
+// * 步骤4-2、删除保存回传文件信息的文件
+// */
+// if(file.exists()){
+// file.delete();
+// }
+// /**
+// * 步骤4-3、正常回传完成,删除临时文件
+// */
+// if(tempDir!=null && tempDir.exists()){
+// try {
+// FileUtils.deleteDirectory(tempDir);
+// } catch (IOException e) {
+// }
+// }
+// }else{
+// /**
+// * 步骤4-1 将下次需要回传的文件重新写入文件
+// */
+// rfPo.setResDesc(sb.toString());
+// String[] values = new String[] { JSONObject.fromObject(
+// rfPo).toString() };
+// FileWrUtil.cfgFilePrinter(file, Contants.charset,
+// values);
+// }
+// } catch (Exception e) {
+// logger.error(Utils.printExceptionStack(e));
+// }finally{
+// if(tempDir!=null && tempDir.exists() && tempDir.listFiles().length==0){
+// try {
+// FileUtils.deleteDirectory(tempDir);
+// } catch (IOException e) {
+// }
+// }
+// }
+// return;
+// }
+
+
+ //----------打包上传数据中的部分代码
+ //移动文件到临时文件
+ /*File destDir = new File(Contants.localDataCollection + File.separator + "temp_data");
+ for(File dir : dataDirs){
+ File[] files = FileUtil.getFilesEndWith(dir, ".csv");
+ if (files == null || files.length <= 0) {
+ continue;
+ }
+ for(File file : files){
+ FileUtil.moveFile(file, destDir.getAbsolutePath(), dir.getName(), true);
+ }
+ }
+ //压缩文件
+ String compressFileStr = Contants.localDataCollection
+ + File.separator
+ + CommonSocket.addTimeTagForFileName("detectdata",
+ null)
+ + CompressFileMgr.getCompressSuffixByOs(false);
+ new CompressFileMgr().compressFile(destDir
+ .getAbsolutePath(), compressFileStr, null, false);
+ //删除临时文件
+ FileUtils.deleteDirectory(destDir);*/
+}
diff --git a/src/test/TestNet.java b/src/test/TestNet.java
new file mode 100644
index 0000000..e33da29
--- /dev/null
+++ b/src/test/TestNet.java
@@ -0,0 +1,151 @@
+package test;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.Scanner;
+
+import org.hyperic.sigar.FileSystem;
+import org.hyperic.sigar.FileSystemUsage;
+import org.hyperic.sigar.NetFlags;
+import org.hyperic.sigar.NetInterfaceConfig;
+import org.hyperic.sigar.NetInterfaceStat;
+import org.hyperic.sigar.Sigar;
+import org.hyperic.sigar.SigarException;
+
+
+public class TestNet {
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ try {
+ Sigar sigar = new Sigar();
+
+ FileSystem fslist[] = sigar.getFileSystemList();
+ for (int i = 0; i < fslist.length; i++) {
+ FileSystem fs = fslist[i];
+ try {
+ FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
+ if (fs.getType() == 2) {// 先取每个盘符的大小和剩余空间
+ OutputStreamWriter fos = null;
+ File file = new File(fs.getDirName() + File.separator + "writetest.temp");
+ System.out.println("-----------file path--" + file.getAbsolutePath());
+ try {
+ String testStr = "测试硬盘是否可写,现在开始写入文件";
+ fos = new OutputStreamWriter(
+ new FileOutputStream(file), "utf-8");
+ fos.write(testStr);
+ fos.flush();
+ } catch (IOException e) {
+ System.out.println("测试硬盘是否可写:" + e.getMessage());
+ }finally {
+ if(fos!=null){
+ try {
+ fos.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ if(file.exists()){
+ file.delete();
+ System.out.println("---------file delete=" + file.getAbsolutePath());
+ }
+ }
+ } catch (SigarException e) {
+ if (fs.getType() == 2)
+ throw e;
+ continue;
+ }
+ }
+
+ String ifNames[] = sigar.getNetInterfaceList();
+ if(ifNames.length >0){
+ System.out.println("========= all list ==========");
+ for (int i = 0; i < ifNames.length; i++) {
+ String name = ifNames[i];
+ try {
+ NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
+ System.out
+ .println(name
+ + "\t"
+ + ifconfig.getType()
+ + "\t"
+ + ifconfig.getFlags()
+ + "---((ifconfig.getFlags()&NetFlags.IFF_POINTOPOINT)>0)="
+ + ((ifconfig.getFlags() & NetFlags.IFF_POINTOPOINT) > 0)
+ + "---((ifconfig.getFlags()&NetFlags.IFF_LOOPBACK)>0)="
+ + ((ifconfig.getFlags() & NetFlags.IFF_LOOPBACK) > 0)
+ + "---((ifconfig.getFlags()&NetFlags.IFF_BROADCAST)<=0)="
+ + ((ifconfig.getFlags() & NetFlags.IFF_BROADCAST) <= 0)
+ + "---((ifconfig.getFlags()&NetFlags.IFF_MULTICAST)<=0)="
+ + ((ifconfig.getFlags() & NetFlags.IFF_MULTICAST) <= 0)
+ + "\t---((ifconfig.getFlags()&NetFlags.IFF_UP)<=0)="
+ + ((ifconfig.getFlags() & NetFlags.IFF_UP) <= 0));
+ } catch (SigarException e) {
+ System.out.println(name);
+ continue;
+ }
+ }
+
+ System.out.println("========= net list ==========");
+ for (int i = 0; i < ifNames.length; i++) {
+ String name = ifNames[i];
+ try {
+ NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
+ // *** 网卡类型:ethernet, Local Loopback(本地环回网卡)
+ /*if (!"ethernet".equalsIgnoreCase(ifconfig.getType())) {
+ continue;
+ }*/
+ // *** 这里只取 ethernet 网卡类型
+
+ if ((ifconfig.getFlags() & NetFlags.IFF_POINTOPOINT) > 0) {
+ continue;
+ }
+ if ((ifconfig.getFlags() & NetFlags.IFF_LOOPBACK) > 0) {
+ continue;
+ }
+ if ((ifconfig.getFlags() & NetFlags.IFF_BROADCAST) <= 0) {// broadcast地址无效
+ continue;
+ }
+ if ((ifconfig.getFlags() & NetFlags.IFF_MULTICAST) <= 0) {// 不支持multicast
+ continue;
+ }
+ if ((ifconfig.getFlags() & NetFlags.IFF_UP) <= 0) {
+ continue;
+ }
+ System.out.println(name + "--" + ifconfig.getAddress());
+ } catch (SigarException e) {
+ continue;
+ }
+ }
+
+ Scanner sc = new Scanner(System.in);
+ while(true){
+ System.out.print("\nplease enter net name:");
+ String name = sc.nextLine();
+ if("quit".equalsIgnoreCase(name)){
+ break;
+ }
+ if(name==null || "".equals(name)){
+ continue;
+ }
+ System.out.println("-----------" + name + "------------");
+ try{
+ NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
+ System.out.println("speed: " + ifstat.getSpeed() + "b/s\nRxPackets: " + ifstat.getRxPackets() + "\nTxPackets: " + ifstat.getTxPackets());
+ } catch (SigarException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ } catch (SigarException e) {
+ System.err.println("获取网络信息异常");
+ e.printStackTrace();
+ }
+ }
+
+}