Список полезных настроек среды в Java - PullRequest
27 голосов
/ 28 сентября 2011

Я долго размышлял, существует ли полный список (возможно, статических) методов / полей, в которых хранится информация времени выполнения для JVM.Неполный список примеров:

  • System.out / System.in
  • System.currentTimeMillis ()
  • System.getProperty ()
  • System.getConsole ()
  • Runtime.freeMemory ()
  • и т. Д.

У кого-нибудь есть ссылка или что-то?

РЕДАКТИРОВАТЬ: I 'Я не настолько глуп, чтобы не проверять документы на System и Runtime: PI просто задавался вопросом, существуют ли другие классы, где хранятся похожие методы для определения состояния компьютера, на котором вы работаете.

Ответы [ 2 ]

36 голосов
/ 01 октября 2011

Общие свойства

Я использую этот код, чтобы получить представление о некоторых вещах, известных классам Java, которые представляют для меня особый интерес.

System Properties

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.*;

import java.security.*;

/** A small GUId app. that shows many system and environment properties.
Designed to be compatible with Java 1.4+ (hence many requirements like
no foreach, no generics, no StringBuilder..).
@author Andrew Thompson
@version 2008-06-29
 */
class SystemProperties {

    static String sentence = "The quick brown fox jumped over the lazy dog.";
    static String sep = System.getProperty("line.separator");
    static String fontText =
            sentence +
            sep +
            sentence.toUpperCase() +
            sep +
            "0123456789 !@#$%^&*()_+ []\\;',./ {}|:\"<>?";

    static String[] convertObjectToSortedStringArray(Object[] unsorted) {
        String[] sorted = new String[unsorted.length];
        for (int ii = 0; ii < sorted.length; ii++) {
            sorted[ii] = (String) unsorted[ii];
        }
        Arrays.sort(sorted);
        return sorted;
    }

    static String dataPairToTableRow(String property, Object value) {
        String val = valueToString(property, value);
        return "<tr>" +
                "<th>" +
                "<code>" +
                property +
                "</code>" +
                "</th>" +
                "<td>" +
                val +
                "</td>" +
                "</tr>";
    }

    static String valueToString(String property, Object value) {
        if (value instanceof Color) {
            Color color = (Color) value;
            String converted =
                    "<div style='width: 100%; height: 100%; " +
                    "background-color: #" +
                    Integer.toHexString(color.getRed()) +
                    Integer.toHexString(color.getGreen()) +
                    Integer.toHexString(color.getBlue()) +
                    ";'>" +
                    value.toString() +
                    "</div>";
            return converted;
        } else if (property.toLowerCase().endsWith("path") ||
                property.toLowerCase().endsWith("dirs")) {
            return delimitedToHtmlList(
                    (String) value,
                    System.getProperty("path.separator"));
        } else {
            return value.toString();
        }
    }

    static String delimitedToHtmlList(String values, String delimiter) {
        String[] parts = values.split(delimiter);
        StringBuffer sb = new StringBuffer();
        sb.append("<ol>");
        for (int ii = 0; ii < parts.length; ii++) {
            sb.append("<li>");
            sb.append(parts[ii]);
            sb.append("</li>");
        }
        return sb.toString();
    }

    static Component getExampleOfFont(String fontFamily) {
        Font font = new Font(fontFamily, Font.PLAIN, 24);
        JTextArea ta = new JTextArea();
        ta.setFont(font);
        ta.setText(fontText);
        ta.setEditable(false);
        // don't allow these to get focus, as it
        // interferes with desired scroll behavior
        ta.setFocusable(false);
        return ta;
    }

    static public JScrollPane getOutputWidgetForContent(String content) {
        JEditorPane op = new JEditorPane();
        op.setContentType("text/html");
        op.setEditable(false);

        op.setText(content);

        return new JScrollPane(op);
    }

    public static void main(String[] args) {
        JTabbedPane tabPane = new JTabbedPane();
        StringBuffer sb;
        String header = "<html><body><table border=1 width=100%>";

        sb = new StringBuffer(header);
        Properties prop = System.getProperties();
        String[] propStrings = convertObjectToSortedStringArray(
                prop.stringPropertyNames().toArray());
        for (int ii = 0; ii < propStrings.length; ii++) {
            sb.append(
                    dataPairToTableRow(
                    propStrings[ii],
                    System.getProperty(propStrings[ii])));
        }
        tabPane.addTab(
                "System",
                getOutputWidgetForContent(sb.toString()));

        sb = new StringBuffer(header);
        Map environment = System.getenv();
        String[] envStrings = convertObjectToSortedStringArray(
                environment.keySet().toArray());
        for (int ii = 0; ii < envStrings.length; ii++) {
            sb.append(
                    dataPairToTableRow(
                    envStrings[ii],
                    environment.get(envStrings[ii])));
        }
        tabPane.addTab(
                "Environment",
                getOutputWidgetForContent(sb.toString()));

        sb = new StringBuffer(header);
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();
        for (int j = 0; j < gs.length; j++) {
            GraphicsDevice gd = gs[j];
            sb.append(
                    dataPairToTableRow(
                    "Device " + j,
                    gd.toString() +
                    "  " +
                    gd.getIDstring()));
            GraphicsConfiguration[] gc =
                    gd.getConfigurations();
            for (int i = 0; i < gc.length; i++) {
                sb.append(
                        dataPairToTableRow(
                        "Config " +
                        i,
                        (int) gc[i].getBounds().getWidth() +
                        "x" +
                        (int) gc[i].getBounds().getHeight() +
                        " " +
                        gc[i].getColorModel() +
                        ", " +
                        "  Accelerated: " +
                        gc[i].getImageCapabilities().isAccelerated() +
                        "  True Volatile: " +
                        gc[i].getImageCapabilities().isTrueVolatile()));
            }
        }
        tabPane.addTab(
                "Graphics Environment",
                getOutputWidgetForContent(sb.toString()));

        String[] fonts = ge.getAvailableFontFamilyNames();
        JPanel fontTable = new JPanel(new BorderLayout(3, 1));
        // to enable key based scrolling in the font panel
        fontTable.setFocusable(true);
        JPanel fontNameCol = new JPanel(new GridLayout(0, 1, 2, 2));
        JPanel fontExampleCol = new JPanel(new GridLayout(0, 1, 2, 2));
        fontTable.add(fontNameCol, BorderLayout.WEST);
        fontTable.add(fontExampleCol, BorderLayout.CENTER);
        for (int ii = 0; ii < fonts.length; ii++) {
            fontNameCol.add(new JLabel(fonts[ii]));
            fontExampleCol.add(getExampleOfFont(fonts[ii]));
        }
        tabPane.add("Fonts", new JScrollPane(fontTable));

        sb = new StringBuffer(header);

        sb.append("<thead>");
        sb.append("<tr>");
        sb.append("<th>");
        sb.append("Code");
        sb.append("</th>");
        sb.append("<th>");
        sb.append("Language");
        sb.append("</th>");
        sb.append("<th>");
        sb.append("Country");
        sb.append("</th>");
        sb.append("<th>");
        sb.append("Variant");
        sb.append("</th>");
        sb.append("</tr>");
        sb.append("</thead>");

        Locale[] locales = Locale.getAvailableLocales();
        SortableLocale[] sortableLocale = new SortableLocale[locales.length];
        for (int ii = 0; ii < locales.length; ii++) {
            sortableLocale[ii] = new SortableLocale(locales[ii]);
        }
        Arrays.sort(sortableLocale);
        for (int ii = 0; ii < locales.length; ii++) {
            String prefix = "";
            String suffix = "";
            Locale locale = sortableLocale[ii].getLocale();
            if (locale.equals(Locale.getDefault())) {
                prefix = "<b>";
                suffix = "</b>";
            }
            sb.append(dataPairToTableRow(
                    prefix +
                    locale.toString() +
                    suffix,
                    prefix +
                    locale.getDisplayLanguage() +
                    suffix +
                    "</td><td>" +
                    prefix +
                    locale.getDisplayCountry() +
                    suffix +
                    "</td><td>" +
                    prefix +
                    locale.getDisplayVariant() +
                    suffix));
        }
        tabPane.add("Locales",
                getOutputWidgetForContent(sb.toString()));

        Locale.getDefault();
        int border = 5;
        JPanel p = new JPanel(new BorderLayout());
        p.setBorder(new EmptyBorder(border, border, border, border));
        p.add(tabPane, BorderLayout.CENTER);
        p.setPreferredSize(new Dimension(400, 400));
        JFrame f = new JFrame("Properties");
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.getContentPane().add(p, BorderLayout.CENTER);
        f.pack();
        f.setMinimumSize(f.getPreferredSize());
        f.setSize(600, 500);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

class SortableLocale implements Comparable {

    Locale locale;

    SortableLocale(Locale locale) {
        this.locale = locale;
    }

    public String toString() {
        return locale.toString();
    }

    public Locale getLocale() {
        return locale;
    }

    public int compareTo(Object object2) {
        SortableLocale locale2 = (SortableLocale) object2;
        //Locale locale2 = (Locale)object2;
        return locale.toString().compareTo(
                locale2.toString());
    }
}

Медиа

Свойства, относящиеся к синтезированному и сэмплированному звуку и изображениям.

Media Types

/*
<applet
    code='MediaTypes'
    width='900'
    height='600'>
<param name='show' value='Sound|Sampled|Mixers|Primary Sound Capture Driver'>
</applet>
*/
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.sound.midi.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.swing.text.Position;

public class MediaTypes extends JApplet {

    JTable table;
    boolean sortable = false;
    JTree tree;

    @Override
    public void init() {
        Runnable r = () -> {
            MediaTypes mediaTypes = new MediaTypes();

            String show = "";
            if (getParameter("show")!=null) {
                show = getParameter("show");
            }

            JPanel p = new JPanel();
            mediaTypes.createGui(p, show);
            add(p);
            validate();
        };
        SwingUtilities.invokeLater(r);
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            MediaTypes mediaTypes = new MediaTypes();

            JPanel p = new JPanel();
            mediaTypes.createGui(p);
            JOptionPane.showMessageDialog(null,p);
        };
        SwingUtilities.invokeLater(r);
    }

    public Object[][] mergeArrays(String name1, Object[] data1, String name2, Object[] data2) {
        Object[][] data = new Object[data1.length+data2.length][2];
        for (int ii=0; ii<data1.length; ii++) {
            data[ii][0] = name1;
            data[ii][1] = data1[ii];
        }
        int offset = data1.length;
        for (int ii=offset; ii<data.length; ii++) {
            data[ii][0] = name2;
            data[ii][1] = data2[ii-offset];
        }
        return data;
    }

    public void createGui(JPanel panel) {
        createGui(panel, "");
    }

    public String getShortLineName(String name) {
        String[] lineTypes = {
            "Clip",
            "SourceDataLine",
            "TargetDataLine",
            "Speaker",
            "Microphone",
            "Master Volume",
            "Line In"
        };
        for (String shortName : lineTypes) {
            if ( name.toLowerCase().replaceAll("_", " ").contains(shortName.toLowerCase() )) {
                return shortName;
            }
        }
        return name;
    }

    public void createGui(JPanel panel, String path) {

        //DefaultMutableTreeNode selected = null;

        panel.setLayout( new BorderLayout(5,5) );
        final JLabel output = new JLabel("Select a tree leaf to see the details.");
        panel.add(output, BorderLayout.SOUTH);

        table = new JTable();
        try {
            table.setAutoCreateRowSorter(true);
            sortable = true;
        } catch (Throwable ignore) {
            // 1.6+ functionality - not vital
        }
        JScrollPane tableScroll = new JScrollPane(table);
        Dimension d = tableScroll.getPreferredSize();
        d = new Dimension(450,d.height);
        tableScroll.setPreferredSize(d);
        panel.add( tableScroll, BorderLayout.CENTER );

        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Media");
        DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);

        DefaultMutableTreeNode imageNode = new DefaultMutableTreeNode("Image");
        rootNode.add(imageNode);

        Object[][] data;
        int offset;
        String[] columnNames;

        data = mergeArrays(
            "Reader",
            ImageIO.getReaderFileSuffixes(),
            "Writer",
            ImageIO.getWriterFileSuffixes() );
        columnNames = new String[]{"Input/Output", "Image File Suffixes"};
        MediaData md = new MediaData( "Suffixes", columnNames, data);
        imageNode.add(new DefaultMutableTreeNode(md));

        data = mergeArrays(
            "Reader",
            ImageIO.getReaderMIMETypes(),
            "Writer",
            ImageIO.getWriterMIMETypes() );
        columnNames = new String[]{"Input/Output", "Image MIME Types"};
        md = new MediaData( "MIME", columnNames, data);
        imageNode.add(new DefaultMutableTreeNode(md));

        DefaultMutableTreeNode soundNode = new DefaultMutableTreeNode("Sound");
        rootNode.add(soundNode);

        DefaultMutableTreeNode soundSampledNode = new DefaultMutableTreeNode("Sampled");
        soundNode.add(soundSampledNode);

        md = new MediaData("Suffixes", "Sound File Suffixes", AudioSystem.getAudioFileTypes());
        soundSampledNode.add(new DefaultMutableTreeNode(md));

        Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
        String[][] mixerData = new String[mixerInfo.length][4];
        for (int ii=0; ii<mixerData.length; ii++) {
            mixerData[ii][0] = mixerInfo[ii].getName();
            mixerData[ii][1] = mixerInfo[ii].getVendor();
            mixerData[ii][2] = mixerInfo[ii].getVersion();
            mixerData[ii][3] = mixerInfo[ii].getDescription();
        }
        columnNames = new String[]{"Name", "Vendor", "Version", "Description"};
        md = new MediaData("Mixers", columnNames, mixerData);
        DefaultMutableTreeNode soundSampledMixersNode = new DefaultMutableTreeNode(md);
        soundSampledNode.add(soundSampledMixersNode);

        for (Mixer.Info mixerInfo1 : mixerInfo) {
            Mixer mixer = AudioSystem.getMixer(mixerInfo1);
            data = mergeArrays(
                    "Source",
                    mixer.getSourceLineInfo(),
                    "Target",
                    mixer.getTargetLineInfo() );
            columnNames = new String[]{ "Input/Output", "Line Info" };
            md = new MediaData(mixerInfo1.getName(), columnNames, data);
            DefaultMutableTreeNode soundSampledMixerNode = new DefaultMutableTreeNode(md);
            soundSampledMixersNode.add( soundSampledMixerNode );
            Line.Info[] source = mixer.getSourceLineInfo();
            Line.Info[] target = mixer.getTargetLineInfo();
            Line[] all = new Line[source.length + target.length];
            try {
                for (int jj=0; jj<source.length; jj++) {
                    all[jj] = AudioSystem.getLine(source[jj]);
                }
                for (int jj=source.length; jj<all.length; jj++) {
                    all[jj] = AudioSystem.getLine(target[jj-source.length]);
                }
                columnNames = new String[]{"Attribute", "Value"};
                for (Line line : all) {
                    Control[] controls = line.getControls();
                    if (line instanceof DataLine) {
                        DataLine dataLine = (DataLine)line;
                        AudioFormat audioFormat = dataLine.getFormat();
                        data = new Object[7+controls.length][2];

                        data[0][0] = "Channels";
                        data[0][1] = audioFormat.getChannels();

                        data[1][0] = "Encoding";
                        data[1][1] = audioFormat.getEncoding();

                        data[2][0] = "Frame Rate";
                        data[2][1] = audioFormat.getFrameRate();

                        data[3][0] = "Sample Rate";
                        data[3][1] = audioFormat.getSampleRate();

                        data[4][0] = "Sample Size (bits)";
                        data[4][1] = audioFormat.getSampleSizeInBits();

                        data[5][0] = "Big Endian";
                        data[5][1] = audioFormat.isBigEndian();

                        data[6][0] = "Level";
                        data[6][1] = dataLine.getLevel();

                    } else if (line instanceof Port) {
                        Port port = (Port)line;
                        Port.Info portInfo = (Port.Info)port.getLineInfo();
                        data = new Object[2+controls.length][2];

                        data[0][0] = "Name";
                        data[0][1] = portInfo.getName();

                        data[1][0] = "Source";
                        data[1][1] = portInfo.isSource();
                    } else {
                        System.out.println( "?? " + line );
                    }
                    int start = data.length-controls.length;
                    for (int kk=start; kk<data.length; kk++) {
                        data[kk][0] = "Control";
                        int index = kk-start;
                        data[kk][1] = controls[index];
                    }
                    md = new MediaData(getShortLineName(line.getLineInfo().toString()), columnNames, data);
                    soundSampledMixerNode.add(new DefaultMutableTreeNode(md));
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }

        int[] midiTypes = MidiSystem.getMidiFileTypes();
        data = new Object[midiTypes.length][2];
        for (int ii=0; ii<midiTypes.length; ii++) {
            data[ii][0] = midiTypes[ii];
            String description = "Unknown";
            switch (midiTypes[ii]) {
                case 0:
                    description = "Single Track";
                    break;
                case 1:
                    description = "Multi Track";
                    break;
                case 2:
                    description = "Multi Song";
            }
            data[ii][1] = description;
        }
        columnNames = new String[]{"Type", "Description"};
        md = new MediaData("MIDI", columnNames, data);
        DefaultMutableTreeNode soundMIDINode = new DefaultMutableTreeNode(md);
        soundNode.add(soundMIDINode);

        columnNames = new String[]{
            "Attribute",
            "Value"};
        MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo() ;
        for (MidiDevice.Info midiDeviceInfo1 : midiDeviceInfo) {
            data = new Object[6][2];
            data[0][0] = "Name";
            data[0][1] = midiDeviceInfo1.getName();
            data[1][0] = "Vendor";
            data[1][1] = midiDeviceInfo1.getVendor();
            data[2][0] = "Version";
            String version = midiDeviceInfo1.getVersion();
            data[2][1] = version.replaceAll("Version ", "");
            data[3][0] = "Description";
            data[3][1] = midiDeviceInfo1.getDescription();
            data[4][0] = "Maximum Transmitters";
            data[5][0] = "Maximum Receivers";
            try {
                MidiDevice midiDevice = MidiSystem.getMidiDevice(midiDeviceInfo1);
                Object valueTransmitter;
                if (midiDevice.getMaxTransmitters()==AudioSystem.NOT_SPECIFIED) {
                    valueTransmitter = "Not specified";
                } else {
                    valueTransmitter = midiDevice.getMaxTransmitters();
                }
                Object valueReceiver;
                if (midiDevice.getMaxReceivers()==AudioSystem.NOT_SPECIFIED) {
                    valueReceiver = "Not specified";
                } else {
                    valueReceiver = midiDevice.getMaxReceivers();
                }
                data[4][1] = valueTransmitter;
                data[5][1] = valueReceiver;
            }catch(MidiUnavailableException mue) {
                data[4][1] = "Unknown";
                data[5][1] = "Unknown";
            }
            md = new MediaData(midiDeviceInfo1.getName(), columnNames, data);
            soundMIDINode.add( new DefaultMutableTreeNode(md) );
        }

        tree = new JTree(treeModel);
        tree.setRootVisible(false);
        tree.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.addTreeSelectionListener((TreeSelectionEvent tse) -> {
            if (sortable) {
                output.setText("Click table column headers to sort.");
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                    tree.getLastSelectedPathComponent();

            if (node == null) return;

            Object nodeInfo = node.getUserObject();
            if (nodeInfo instanceof MediaData) {
                MediaData mediaData = (MediaData)nodeInfo;
                table.setModel( new DefaultTableModel(
                        mediaData.getData(),
                        mediaData.getColumnNames()) );
            }
        });

        for (int ii=0; ii<tree.getRowCount(); ii++) {
            tree.expandRow(ii);
        }

        String[] paths = path.split("\\|");
        int row = 0;
        TreePath treePath = null;
        for (String prefix : paths) {
            treePath = tree.getNextMatch( prefix, row, Position.Bias.Forward );
            row = tree.getRowForPath(treePath);
        }

        panel.add(new JScrollPane(tree),BorderLayout.WEST);

        tree.setSelectionPath(treePath);
        tree.scrollRowToVisible(row);
    }
}

class MediaData {

    String name;
    String[] columnNames;
    Object[][] data;

    MediaData(String name, String columnName, Object[] data) {
        this.name = name;

        columnNames = new String[1];
        columnNames[0] = columnName;

        this.data = new Object[data.length][1];
        for (int ii=0; ii<data.length; ii++) {
            this.data[ii][0] = data[ii];
        }
    }

    MediaData(String name, String[] columnNames, Object[][] data) {
        this.name = name;
        this.columnNames = columnNames;
        this.data = data;
    }

    @Override
    public String toString() {
        return name;
    }

    public String[] getColumnNames() {
        return columnNames;
    }

    public Object[][] getData() {
        return data;
    }
}

Другое

Вы также можетерасследовать:

  • InetAddress
  • KeyStore
  • Менеджеры
    • CookieManager
    • KeyManagerFactory
    • LogManager
4 голосов
/ 23 ноября 2016

Этот класс печатает довольно много вещей на стандартный вывод

import java.util.Properties;
import java.util.logging.LogManager;

import javax.net.ssl.KeyManagerFactory;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map.Entry;
import java.awt.DisplayMode;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.ImageCapabilities;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class JavaInfo {

    public static PrintStream out = System.out;

    public static void printCurrentTime() {
        out.println("current date " + new Date());
        out.println("nano time "+System.nanoTime());        
    }

    public static void printSystemEnvironment() {
        for (Entry<String,String> e : System.getenv().entrySet())
            out.println(e.getKey()+" "+e.getValue());
    }

    public static void printSystemProperties() {
        Properties props = System.getProperties();
        Enumeration<Object> enums = props.keys();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement().toString();
            out.println(key + " : " + props.getProperty(key));
        }
    }

    public static void printRuntimeMemory() {
        Runtime r = Runtime.getRuntime();
        out.println("free memory " + r.freeMemory());
        out.println("max memory " + r.maxMemory());
        out.println("total memory " + r.totalMemory());
    }

    public static void printCommandLineArguments() {
        out.print("JVM arguments");
        for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments())
            out.print(" "+arg);
        out.println();
    }

    public static void printClassLoaderInfo() {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        out.println("thread context class loader "+cl.getClass().getName());
        out.println("system class loader "+ClassLoader.getSystemClassLoader().getClass().getName());
        ClassLoadingMXBean cx = ManagementFactory.getClassLoadingMXBean();
        out.println("loaded classes count "+cx.getLoadedClassCount());
    }

    public static void printOSInfo() {
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        out.println("OS name "+os.getName()+" version "+os.getVersion());
        out.println("architecture "+os.getArch());
        out.println("available processors "+os.getAvailableProcessors());
    }

    public static void printCPUUsage() {
        out.println("Current thread CPU time "+ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime());
        out.println("number of threads "+ManagementFactory.getThreadMXBean().getThreadCount());     
        out.println("system load average "+ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage());        
    }

    public static void printDisplayInfo() {
        int g = 0;
        for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
            out.println("graphics device #"+(++g)+": "+gd.getIDstring()+" type "+gd.getType());
            out.println("\tavailable accelerated memory " + gd.getAvailableAcceleratedMemory());
            int c = 0;
            for (GraphicsConfiguration gc : gd.getConfigurations()) {
                out.println("\tgraphics configuration #"+(++c)+":");
                out.println("\t\twidth "+gc.getBounds().getWidth()+" height "+gc.getBounds().getHeight());
                out.println("\t\tfull screen "+gc.getBufferCapabilities().isFullScreenRequired());
                ImageCapabilities ic = gc.getImageCapabilities();
                out.println("\t\tis accelerated "+ic.isAccelerated());

            }
            DisplayMode dm = gd.getDisplayMode();   
            out.println("\tdisplay mode bit width "+dm.getWidth()+" height "+dm.getHeight()+" bit depth "+dm.getBitDepth()+" refresh rate "+dm.getRefreshRate());
            int m = 0;
            for (DisplayMode d : gd.getDisplayModes())
                out.println("\talt display mode #"+(++m)+" bit width "+d.getWidth()+" height "+d.getHeight()+" bit depth "+d.getBitDepth()+" refresh rate "+d.getRefreshRate());    
        }
    }

    public static void printFontsInfo() {
        out.println("available fonts: "+String.join(",", GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()));
    }

    public static void printLocaleInfo() {
        out.println("default locale: "+Locale.getDefault().getDisplayName()+" country "+Locale.getDefault().getCountry()+" language "+Locale.getDefault().getLanguage());
        out.println("available locales:");
        for (Locale l : Locale.getAvailableLocales())
            out.println("\t"+l.getDisplayName()+" country "+l.getCountry()+" language "+l.getLanguage());
    }

    public static void printDiskInfo() {
        System.out.println("Current directory: "+Paths.get(".").toAbsolutePath().normalize().toString());
        File[] roots = File.listRoots();
        for (File r : roots) {
              out.println("File system root: " + r.getAbsolutePath());
              out.println("\tTotal space (bytes): " + r.getTotalSpace());
              out.println("\tFree space (bytes): " + r.getFreeSpace());
              out.println("\tUsable space (bytes): " + r.getUsableSpace());
              out.println("\tcan write "+r.canWrite());
            }
    }

    public static void printNetworkInfo() throws UnknownHostException {
        out.println("host name "+InetAddress.getLocalHost().getHostName());
        out.println("host IP address "+InetAddress.getLocalHost().getHostAddress());

    }

    public static void printSecurityInfo() throws UnknownHostException {
        SecurityManager security = System.getSecurityManager();
         if (security != null) {
             out.println("security manager "+security.getClass().getName()+" in check "+security.getInCheck());

         } else {
             out.println("no security manager");
         }
    }

    public static void printKeyManagerInfo() {
        out.println("key manager default algorithm "+KeyManagerFactory.getDefaultAlgorithm());      
        out.println("key store default type "+KeyStore.getDefaultType());
    }

    public static void printLoggingInfo() {
        for (String logger : LogManager.getLoggingMXBean().getLoggerNames()) {
            out.println("logger: \""+logger+"\" level \""+LogManager.getLoggingMXBean().getLoggerLevel(logger)+"\"");
        }

    }

    public static void main(String args []) throws Exception {

        out.println("****************************************");
        out.println("DATE INFO");
        printCurrentTime();
        out.println("");
        out.println("****************************************");
        out.println("JVM COMMAND LINE ARGUMENTS");
        printCommandLineArguments();
        out.println("");
        out.println("****************************************");
        out.println("ENVIRONMENT");
        printSystemEnvironment();
        out.println("");
        out.println("****************************************");
        out.println("SYSTEM PROPERTIES");
        printSystemProperties();
        out.println("");
        out.println("****************************************");
        out.println("CLASS LOADER");
        printClassLoaderInfo();
        out.println("");
        out.println("****************************************");
        out.println("OPERATING SYSTEM");
        printOSInfo();
        out.println("");
        out.println("****************************************");
        out.println("MEMORY");
        printRuntimeMemory();
        out.println("");
        out.println("****************************************");
        out.println("CPU");
        printCPUUsage();
        out.println("");
        out.println("****************************************");
        out.println("DISK");
        printDiskInfo();
        out.println("");
        out.println("****************************************");
        out.println("NETWORK");
        printNetworkInfo();
        out.println("");
        out.println("****************************************");
        out.println("SECURITY");
        printSecurityInfo();
        out.println("");
        out.println("");
        out.println("****************************************");
        out.println("LOG");
        printLoggingInfo();
        out.println("");
        out.println("****************************************");
        out.println("KEY MANAGER");
        printKeyManagerInfo();
        out.println("");
        out.println("****************************************");
        out.println("DISPLAY DEVICES");
        printDisplayInfo();
        out.println("");
        out.println("****************************************");
        out.println("FONTS");
        printFontsInfo();
        out.println("");
        out.println("****************************************");
        out.println("LOCALES");
        printLocaleInfo();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...