Java基础-015-System.java常用类

Java基础-015-System.java常用类

java/lang/System.java


1、标准输入输出

System.inSystem.out

java 复制代码
public class Test {
    public static void main(String[] args) {
        String charsetName = String.valueOf(Charset.defaultCharset());
        System.out.println("System.out.println : charsetName="+charsetName);
        Scanner s = new Scanner(System.in,"gbk");
        if (s.hasNext()) {
            String str1 = s.next();
            System.out.println("输入的数据为:" + str1);
        }
    }
}

2、获取属性

jdk/internal/util/SystemProps.javajava/lang/VersionProps.javajdk/internal/util/StaticProperty.java

java 复制代码
System.out.println("System.getProperty(\"sun.jnu.encoding\")="+System.getProperty("sun.jnu.encoding"));
System.out.println("System.getProperty(\"native.encoding\")="+System.getProperty("native.encoding"));
System.out.println("System.getProperty(\"sun.stdout.encoding\")="+System.getProperty("sun.stdout.encoding"));
System.out.println("System.getProperty(\"user.dir\")="+System.getProperty("user.dir"));
System.out.println("System.getProperties()="+System.getProperties());
xml 复制代码
System.getProperties()={java.specification.version=18, sun.cpu.isalist=amd64, sun.jnu.encoding=GBK, java.class.path=D:\IdeaProjects\Jcmd\build\classes\java\main;D:\IdeaProjects\Jcmd\build\resources\main;D:\gradle\envs\caches\modules-2\files-2.1\com.gitee.xhbruce.xhLog\xLog\1.0.3\8734bf5379ee7cee34cf10ab875570208b2360ca\xLog-1.0.3.jar;D:\gradle\envs\caches\modules-2\files-2.1\org.apache.commons\commons-exec\1.3\8dfb9facd0830a27b1b5f29f84593f0aeee7773b\commons-exec-1.3.jar, java.vm.vendor=Oracle Corporation, sun.arch.data.model=64, user.variant=, java.vendor.url=https://java.oracle.com/, java.vm.specification.version=18, os.name=Windows 10, user.country=CN, sun.java.launcher=SUN_STANDARD, sun.boot.library.path=D:\ProgramFiles\Java\jdk-18.0.1.1\bin, sun.java.command=org.xhbruce.Test, jdk.debug=release, sun.cpu.endian=little, user.home=C:\Users\Administrator, user.language=zh, java.specification.vendor=Oracle Corporation, java.version.date=2022-04-22, java.home=D:\ProgramFiles\Java\jdk-18.0.1.1, file.separator=\, java.vm.compressedOopsMode=Zero based, line.separator=
, java.vm.specification.vendor=Oracle Corporation, java.specification.name=Java Platform API Specification, user.script=, sun.management.compiler=HotSpot 64-Bit Tiered Compilers, java.runtime.version=18.0.1.1+2-6, user.name=xhbruce, path.separator=;, os.version=10.0, java.runtime.name=Java(TM) SE Runtime Environment, file.encoding=UTF-8, java.vm.name=Java HotSpot(TM) 64-Bit Server VM, java.vendor.url.bug=https://bugreport.java.com/bugreport/, java.io.tmpdir=C:\Users\ADMINI~1\AppData\Local\Temp\, java.version=18.0.1.1, user.dir=D:\IdeaProjects\Jcmd, os.arch=amd64, java.vm.specification.name=Java Virtual Machine Specification, sun.os.patch.level=, native.encoding=GBK, java.library.path=D:\ProgramFiles\Java\jdk-18.0.1.1\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\ProgramData\chocolatey\bin;D:\Books\Linux\bat;D:\AndroidStudio\Sdk\tools;D:\AndroidStudio\Sdk\platform-tools;D:\AndroidStudio\Sdk\cmake\3.6.4111459\bin;D:\AndroidStudio;D:\ProgramFiles\Java\Openjfx\javafx-sdk-21\lib;D:\ProgramFiles\Java\jdk-18.0.1.1\bin;D:\ProgramFiles\Java\jdk-18.0.1.1\jre;C:\Program Files\mingw64\bin;%CTAGS_HOME%;%TOMCAT_HOME%\bin;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;D:\ProgramFiles\ffmpeg\bin;D:\gradle\envs;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;C:\Users\Administrator\AppData\Roaming\npm;G:\ProgramFiles\JetBrains\Toolbox\scripts;D:\Program Files\Microsoft VS Code\bin;C:\Users\Administrator\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts;;., java.vm.info=mixed mode, sharing, java.vendor=Oracle Corporation, java.vm.version=18.0.1.1+2-6, sun.io.unicode.encoding=UnicodeLittle, java.class.version=62.0}
属性字段 功能 获取结果
java.specification.version 18
sun.cpu.isalist amd64
sun.jnu.encoding GBK
java.class.path D:\IdeaProjects\Jcmd\build\classes\java\main;...
java.vm.vendor Oracle Corporation
sun.arch.data.model 64
user.variant
java.vendor.url https://java.oracle.com/
java.vm.specification.version 18
os.name 系统名称 Windows 10
user.country 系统国家 CN
sun.java.launcher SUN_STANDARD
sun.boot.library.path D:\ProgramFiles\Java\jdk-18.0.1.1\bin
sun.java.command org.xhbruce.Test
jdk.debug release
sun.cpu.endian little
user.home 系统用户文件夹 C:\Users\Administrator
user.language 系统语言 zh
java.specification.vendor Oracle Corporation
java.version.date java版本日期 2022-04-22
java.home java路径 D:\ProgramFiles\Java\jdk-18.0.1.1
file.separator 文件分隔符 \
java.vm.compressedOopsMode Zero based
line.separator
java.vm.specification.vendor Oracle Corporation
java.specification.name Java Platform API Specification
user.script
sun.management.compiler HotSpot 64-Bit Tiered Compilers
java.runtime.version 18.0.1.1+2-6
user.name xhbruce
path.separator ;
os.version 10.0
java.runtime.name Java™ SE Runtime Environment
file.encoding UTF-8
java.vm.name Java HotSpot™ 64-Bit Server VM
java.vendor.url.bug https://bugreport.java.com/bugreport/
java.io.tmpdir C:\Users\ADMINI~1\AppData\Local\Temp, java.version=18.0.1.1
user.dir 当前路径 D:\IdeaProjects\Jcmd
os.arch amd64
java.vm.specification.name Java Virtual Machine Specification
sun.os.patch.level
native.encoding GBK
java.library.path 系统环境配置path D:\ProgramFiles\Java\jdk-18.0.1.1\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;...
java.vm.info mixed mode, sharing
java.vendor Oracle Corporation
java.vm.version 18.0.1.1+2-6
sun.io.unicode.encoding UnicodeLittle
java.class.version 62.0

3、System.java初始化

  • SystemProps.initProperties()VersionProps.init(tempProps)VM.saveProperties(tempProps)StaticProperty.javaHome()系统属性和java相关属性初始化
  • setIn0setOut0setErr0标准输出输出配置
java 复制代码
    /**
     * Initialize the system class.  Called after thread initialization.
     */
    private static void initPhase1() {

        // register the shared secrets - do this first, since SystemProps.initProperties
        // might initialize CharsetDecoders that rely on it
        setJavaLangAccess();

        // VM might invoke JNU_NewStringPlatform() to set those encoding
        // sensitive properties (user.home, user.name, boot.class.path, etc.)
        // during "props" initialization.
        // The charset is initialized in System.c and does not depend on the Properties.
        Map<String, String> tempProps = SystemProps.initProperties();
        VersionProps.init(tempProps);

        // There are certain system configurations that may be controlled by
        // VM options such as the maximum amount of direct memory and
        // Integer cache size used to support the object identity semantics
        // of autoboxing.  Typically, the library will obtain these values
        // from the properties set by the VM.  If the properties are for
        // internal implementation use only, these properties should be
        // masked from the system properties.
        //
        // Save a private copy of the system properties object that
        // can only be accessed by the internal implementation.
        VM.saveProperties(tempProps);
        props = createProperties(tempProps);

        // Check if sun.jnu.encoding is supported. If not, replace it with UTF-8.
        var jnuEncoding = props.getProperty("sun.jnu.encoding");
        if (jnuEncoding == null || !Charset.isSupported(jnuEncoding)) {
            notSupportedJnuEncoding = jnuEncoding == null ? "null" : jnuEncoding;
            props.setProperty("sun.jnu.encoding", "UTF-8");
        }

        StaticProperty.javaHome();          // Load StaticProperty to cache the property values

        lineSeparator = props.getProperty("line.separator");

        FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
        FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
        FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
        setIn0(new BufferedInputStream(fdIn));
        // sun.stdout/err.encoding are set when the VM is associated with the terminal,
        // thus they are equivalent to Console.charset(), otherwise the encoding
        // defaults to native.encoding
        setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding", StaticProperty.nativeEncoding())));
        setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding", StaticProperty.nativeEncoding())));

        // Setup Java signal handlers for HUP, TERM, and INT (where available).
        Terminator.setup();

        // Initialize any miscellaneous operating system settings that need to be
        // set for the class libraries. Currently this is no-op everywhere except
        // for Windows where the process-wide error mode is set before the java.io
        // classes are used.
        VM.initializeOSEnvironment();

        // The main thread is not added to its thread group in the same
        // way as other threads; we must do it ourselves here.
        Thread current = Thread.currentThread();
        current.getThreadGroup().add(current);

        // Subsystems that are invoked during initialization can invoke
        // VM.isBooted() in order to avoid doing things that should
        // wait until the VM is fully initialized. The initialization level
        // is incremented from 0 to 1 here to indicate the first phase of
        // initialization has completed.
        // IMPORTANT: Ensure that this remains the last initialization action!
        VM.initLevel(1);
    }

4、设置标准输出System.out

java/io/PrintStream.java

  • 主要用于IDE和系统终端输出设置编码Encoding
  • 设置输出到文件



java 复制代码
String stdoutEncoding = System.getProperty("file.encoding")
if (!System.out.charset().name().equals(stdoutEncoding)) {
    try {
        PrintStream ps = new PrintStream(System.out, true, stdoutEncoding);
        System.setOut(ps);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
java 复制代码
System.out.println("#########################");
System.out.println("System.out" + System.out);
try {
    PrintStream ps = new PrintStream(new File(System.getProperty("user.dir")+"/test.txt"), stdoutEncoding);
    System.setOut(ps);
} catch (UnsupportedEncodingException | FileNotFoundException e) {
    throw new RuntimeException(e);
}
System.out.println("System.out" + System.out);
System.out.println("System.out.charset() = " + System.out.charset());
System.out.println("native.encoding = " + System.getProperty("native.encoding"));
System.out.println("sun.jnu.encoding = " + System.getProperty("sun.jnu.encoding"));
System.out.println("sun.stdout.encoding = " + System.getProperty("sun.stdout.encoding"));
System.out.println("sun.io.unicode.encoding = " + System.getProperty("sun.io.unicode.encoding"));
System.out.println("#########################");
System.out.println("你好 java");
XLog.d("你好 xhburce");
相关推荐
无尽的大道3 分钟前
Java字符串深度解析:String的实现、常量池与性能优化
java·开发语言·性能优化
小鑫记得努力12 分钟前
Java类和对象(下篇)
java
binishuaio16 分钟前
Java 第11天 (git版本控制器基础用法)
java·开发语言·git
zz.YE17 分钟前
【Java SE】StringBuffer
java·开发语言
老友@18 分钟前
aspose如何获取PPT放映页“切换”的“持续时间”值
java·powerpoint·aspose
wrx繁星点点33 分钟前
状态模式(State Pattern)详解
java·开发语言·ui·设计模式·状态模式
Upaaui36 分钟前
Aop+自定义注解实现数据字典映射
java
zzzgd81636 分钟前
easyexcel实现自定义的策略类, 最后追加错误提示列, 自适应列宽,自动合并重复单元格, 美化表头
java·excel·表格·easyexcel·导入导出
友善的鸡蛋37 分钟前
解决:使用EasyExcel导入Excel模板时出现数据导入不进去的问题
java·easyexcel·excel导入
星沁城37 分钟前
240. 搜索二维矩阵 II
java·线性代数·算法·leetcode·矩阵