把java工程打成jar無法獲取文件路徑進(jìn)行執(zhí)行與拷貝臨時文件進(jìn)行處理

把java工程打成jar無法獲取文件路徑進(jìn)行執(zhí)行與拷貝臨時文件進(jìn)行處理

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class Main {
    public static void main(String[] args) {
        // 獲取資源文件的路徑
        String resourcePath = getResourcePath1("your-resource-file.txt");
        
        // 執(zhí)行你的代碼
        // ...
    }
    //方法1,此方法是指定文件路徑進(jìn)行拷貝
    
    private static String getResourcePath1(String fileName) {
        try {
            // 指定臨時文件的路徑
            Path tempFilePath = Path.get("path/to/temp/file.txt");
            
            // 從JAR文件中獲取資源文件的輸入流
            InputStream inputStream = Main.class.getResourceAsStream("/" + fileName);
            
            // 將資源文件復(fù)制到指定的臨時文件
            Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回臨時文件的路徑
            return tempFilePath.toAbsolutePath().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    //方法2,此方法是指定文件名稱和格式在臨時路徑生成文件進(jìn)行拷貝
    
    private static String getResourcePath2(String fileName) {
        try {
            // 創(chuàng)建臨時文件,可以指定兩個參數(shù)一個是(prefix前綴名稱和suffix后綴格式)
            
            Path tempFile = Files.createTempFile("test文件", ".txt");
            
            // 從JAR文件中獲取資源文件的輸入流
            InputStream inputStream = Main.class.getResourceAsStream("/" + fileName);
            
            // 將資源文件復(fù)制到臨時文件
            Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回臨時文件的路徑
            return tempFile.toAbsolutePath().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容