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");
相关推荐
积水成江1 小时前
Vite+Vue3+SpringBoot项目如何打包部署
java·前端·vue.js·windows·spring boot·后端·nginx
CocoaAndYy2 小时前
ThreadLocal、InheritableThreadLocal、TransmittableThreadLocal原理及Demo
java·jvm·算法
2401_857439693 小时前
SpringBoot在线教育平台:设计与实现的深度解析
java·spring boot·后端
总是学不会.3 小时前
SpringBoot项目:前后端打包与部署(使用 Maven)
java·服务器·前端·后端·maven
IT学长编程4 小时前
计算机毕业设计 视频点播系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·视频点播系统
一 乐5 小时前
英语词汇小程序小程序|英语词汇小程序系统|基于java的四六级词汇小程序设计与实现(源码+数据库+文档)
java·数据库·小程序·源码·notepad++·英语词汇
曳渔5 小时前
Java-数据结构-反射、枚举 |ू・ω・` )
java·开发语言·数据结构·算法
laocooon5238578865 小时前
java 模拟多人聊天室,服务器与客户机
java·开发语言
风槐啊5 小时前
六、Java 基础语法(下)
android·java·开发语言
苹果醋35 小时前
毕业设计_基于SpringBoot+vue的社区博客系统【源码+SQL+教程+可运行】41002
java·毕业设计·博客