通過System類可以獲取系統中的變量。可以獲取env和System Property。獲取到之後存到D盤的SystemProperties.xls中。具體需要用到什麼系統變量以後就可以在這個xls中查詢了。
程序需要用到POI,我的版本是3.10。如果沒有的話可以在這下載:poi_3.10_FINAL
不想使用POI的童鞋吧for循環裏面的代碼改成System.out.println();輸出即可。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
public class TestJava {
static Map<String , String> env = System.getenv();
static Map<String , String> properties = new HashMap<String , String>();
public static void main(String[] args) {
/*
* Get properties in System and write to XLS File
*/
File file = new File("D:/SystemProperties.xls");
if (file.exists()) {
file.delete();
}
Workbook wb = null;
OutputStream os = null;
try {
file.createNewFile();
os = new FileOutputStream(file);
wb = new HSSFWorkbook();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet = wb.createSheet("env");
CellRangeAddress cra = new CellRangeAddress(0,0,0,1);
sheet.addMergedRegion(cra);
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("env");
row = sheet.createRow(1);
row.createCell(0).setCellValue("Name");
row.createCell(1).setCellValue("Value");
int rownum=2;
Set<Entry<String, String>> set = env.entrySet();
for (Entry<String, String> entry : set) {
row = sheet.createRow(rownum);
row.createCell(0).setCellValue(entry.getKey());
row.createCell(1).setCellValue(entry.getValue());
rownum++;
}
sheet = wb.createSheet("SystemProperties");
sheet.addMergedRegion(cra);
row = sheet.createRow(0);
row.createCell(0).setCellValue("SystemProperties");
row = sheet.createRow(1);
row.createCell(0).setCellValue("Name");
row.createCell(1).setCellValue("Value");;
Properties p = System.getProperties();
Set<String> names = p.stringPropertyNames();
rownum=2;
for (String name : names) {
row = sheet.getRow(rownum);
if (row == null) {
row = sheet.createRow(rownum);
}
row.createCell(0).setCellValue(name);
row.createCell(1).setCellValue(p.getProperty(name));
rownum++;
}
try {
wb.write(os);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}