如何从Java中的静态方法调用getClass()? 获取操作系统的临时文件

2023年 8月 13日 30.1k 0

为什么 getClass() 不能作为静态方法使用?

// 如何从Java中的静态方法调用getClass()?
Java中静态方法不依赖于具体的实例存在,所有不能直接使用this指针,需要别的方式间接的获取到类名。

方法一: new Object(){}.getClass()

InputStream initInputStream = new Object(){}.getClass().getClassLoader().getResourceAsStream(KEYPATH);

方法二:A.class

InputStream initInputStream = A.class.getClassLoader().getResourceAsStream(KEYPATH);

方法三:Thread.currentThread().getContextClassLoader()

ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl.getResourceAsStream(resource);


InputStream 转 FileInputStream

方法一:

InputStream initInputStream = new Object(){}.getClass().getClassLoader().getResourceAsStream(KEYPATH);

byte[] buffer = new byte[initInputStream.available()];
initInputStream.read(buffer);
File targetFile =new File("/tmp");

Files.write(buffer,targetFile);

FileInputStream in = new FileInputStream(targetFile);

是将输入流写到临时文件中,再转为文件流,最后删除临时文件

//创建临时文件
File file = File.createTempFile("certificate","");
FileUtil.writeFromStream(initInputStream,file);
FileInputStream fis = new FileInputStream(file);

 
protected File file;
 

public File writeFromStream(InputStream in) throws IORuntimeException {
    FileOutputStream out = null;

    try {
        out = new FileOutputStream(FileUtil.touch(this.file));
        IoUtil.copy(in, out);
    } catch (IOException var7) {
        throw new IORuntimeException(var7);
    } finally {
        IoUtil.close(out);
    }

    return this.file;
}


public static File touch(File file) throws IORuntimeException {
    if (null == file) {
        return null;
    } else {
        if (!file.exists()) {
            mkParentDirs(file);

            try {
                file.createNewFile();
            } catch (Exception var2) {
                throw new IORuntimeException(var2);
            }
        }

        return file;
    }
}
 
 
 
public static File mkParentDirs(File file) {
    File parentFile = file.getParentFile();
    if (null != parentFile && !parentFile.exists()) {
        parentFile.mkdirs();
    }

    return parentFile;
}
 
 

ClassPathResource 、 new Object() {}.getClass().getClassLoader().getResourceAsStream

protected RSAPrivateKey loadPrivateKeyOfCa() throws UnrecoverableKeyException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException {
    Resource resource = new ClassPathResource(keyPath);
    InputStream in = resource.getInputStream();
    KeyStore ks = KeyStore.getInstance("pkcs12");
    String pword = (String) properties.get("default.password");
    ks.load(in, pword.toCharArray());
    
    
    String alias = ks.aliases().nextElement();
    return (RSAPrivateKey) ks.getKey(alias, password.toCharArray());
}
protected static RSAPrivateKey loadPrivateKeyOfCA() throws UnrecoverableKeyException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException {
    InputStream initInputStream = new Object() {
    }.getClass().getClassLoader().getResourceAsStream(KEYPATH);
    
    //创建临时文件
    File file = File.createTempFile("certificate","");
    FileUtil.writeFromStream(initInputStream,file);
    FileInputStream fis = new FileInputStream(file);

    KeyStore ks = KeyStore.getInstance("pkcs12");
    //证书密码
    ks.load(fis, PASSWORD.toCharArray());
    
    
    String alias = ks.aliases().nextElement();
    RSAPrivateKey caprk = (RSAPrivateKey) ks.getKey(alias, PASSWORD.toCharArray());

    return caprk;
}

 
public static File createTempFile(String prefix, String suffix)
    throws IOException
{
    return createTempFile(prefix, suffix, null);
}
 
 
/**
 * 

Creates a new empty file in the specified directory, using the * given prefix and suffix strings to generate its name. If this method * returns successfully then it is guaranteed that: * * *

  • The file denoted by the returned abstract pathname did not exist * before this method was invoked, and *
  • Neither this method nor any of its variants will return the same * abstract pathname again in the current invocation of the virtual * machine. * * * This method provides only part of a temporary-file facility. To arrange * for a file created by this method to be deleted automatically, use the * {@link #deleteOnExit} method. * *

    The prefix argument must be at least three characters * long. It is recommended that the prefix be a short, meaningful string * such as "hjb" or "mail". The * suffix argument may be null, in which case the * suffix ".tmp" will be used. * *

    To create the new file, the prefix and the suffix may first be * adjusted to fit the limitations of the underlying platform. If the * prefix is too long then it will be truncated, but its first three * characters will always be preserved. If the suffix is too long then it * too will be truncated, but if it begins with a period character * ('.') then the period and the first three characters * following it will always be preserved. Once these adjustments have been * made the name of the new file will be generated by concatenating the * prefix, five or more internally-generated characters, and the suffix. * *

    If the directory argument is null then the * system-dependent default temporary-file directory will be used. The * default temporary-file directory is specified by the system property * java.io.tmpdir. On UNIX systems the default value of this * property is typically "/tmp" or "/var/tmp"; on * Microsoft Windows systems it is typically "C:\WINNT\TEMP". A different * value may be given to this system property when the Java virtual machine * is invoked, but programmatic changes to this property are not guaranteed * to have any effect upon the temporary directory used by this method. * * @param prefix The prefix string to be used in generating the file's * name; must be at least three characters long * * @param suffix The suffix string to be used in generating the file's * name; may be null, in which case the * suffix ".tmp" will be used * * @param directory The directory in which the file is to be created, or * null if the default temporary-file * directory is to be used * * @return An abstract pathname denoting a newly-created empty file * * @throws IllegalArgumentException * If the prefix argument contains fewer than three * characters * * @throws IOException If a file could not be created * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not allow a file to be created * * @since 1.2 */ public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (prefix.length() < 3) throw new IllegalArgumentException("Prefix string too short"); if (suffix == null) suffix = ".tmp"; File tmpdir = (directory != null) ? directory : TempDirectory.location(); SecurityManager sm = System.getSecurityManager(); File f; do { f = TempDirectory.generateFile(prefix, suffix, tmpdir); if (sm != null) { try { sm.checkWrite(f.getPath()); } catch (SecurityException se) { // don't reveal temporary directory location if (directory == null) throw new SecurityException("Unable to create temporary file"); throw se; } } } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); if (!fs.createFileExclusively(f.getPath())) throw new IOException("Unable to create temporary file"); return f; }

  • 获取操作系统的临时文件

    java.io.tmpdir是获取操作系统缓存的临时目录,不同操作系统的缓存临时目录不一样

    Windows: java.io.tmpdir:[C:Users登录用户~1AppDataLocalTemp]
    Solaris: java.io.tmpdir:[/var/tmp/]
    Linux: java.io.tmpdir: [/tmp]

    Mac OS X: java.io.tmpdir: [/tmp]

    System.getProperty()可操作参数还有:

    java.version Java运行时环境版本
    java.vendor Java运行时环境供应商
    java.vendor.url Java供应商的 URL
    java.home Java安装目录 java.vm.specification.version
    Java虚拟机规范版本 java.vm.specification.vendor
    Java虚拟机规范供应商 java.vm.specification.name

    java.vm.version Java虚拟机实现版本
    java.vm.vendorJava 虚拟机实现供应商
    java.vm.name Java虚拟机实现名称
    java.specification.version Java运行时环境规范版本
    java.specification.vendor Java运行时环境规范供应商
    java.specification.name Java运行时环境规范名称
    java.class.version Java类格式版本号
    java.class.path Java类路径
    java.library.path 加载库时搜索的路径列表
    java.io.tmpdir 默认的临时文件路径
    java.compiler 要使用的 JIT 编译器的名称
    java.ext.dirs 一个或多个扩展目录的路径
    os.name 操作系统的名称
    os.arch 操作系统的架构
    os.version 操作系统的版本
    file.separator 文件分隔符(在 UNIX 系统中是“/”)
    path.separator 路径分隔符(在 UNIX 系统中是“:”)
    line.separator 行分隔符(在 UNIX 系统中是“/n”)
    user.name 用户的账户名称
    user.home 用户的主目录
    user.dir 用户的当前工作目录

    
    /* -- Temporary files -- */
    
    private static class TempDirectory {
        private TempDirectory() { }
    
        // temporary directory location
        private static final File tmpdir = new File(AccessController
            .doPrivileged(new GetPropertyAction("java.io.tmpdir")));
        static File location() {
            return tmpdir;
        }
    
        // file name generation
        private static final SecureRandom random = new SecureRandom();
        static File generateFile(String prefix, String suffix, File dir)
            throws IOException
        {
            long n = random.nextLong();
            if (n == Long.MIN_VALUE) {
                n = 0;      // corner case
            } else {
                n = Math.abs(n);
            }
    
            // Use only the file name from the supplied prefix
            prefix = (new File(prefix)).getName();
    
            String name = prefix + Long.toString(n) + suffix;
            File f = new File(dir, name);
            if (!name.equals(f.getName()) || f.isInvalid()) {
                if (System.getSecurityManager() != null)
                    throw new IOException("Unable to create temporary file");
                else
                    throw new IOException("Unable to create temporary file, " + f);
            }
            return f;
        }
    }
    

    相关文章

    服务器端口转发,带你了解服务器端口转发
    服务器开放端口,服务器开放端口的步骤
    产品推荐:7月受欢迎AI容器镜像来了,有Qwen系列大模型镜像
    如何使用 WinGet 下载 Microsoft Store 应用
    百度搜索:蓝易云 – 熟悉ubuntu apt-get命令详解
    百度搜索:蓝易云 – 域名解析成功但ping不通解决方案

    发布评论