Java 我的spring启动应用程序在STS中启动时运行良好,但如果我尝试使用jar,这个方法会杀死它吗?

Java 我的spring启动应用程序在STS中启动时运行良好,但如果我尝试使用jar,这个方法会杀死它吗?,java,spring,spring-boot,Java,Spring,Spring Boot,在Spring工具套件中,应用程序运行良好 在浏览器中运行应用程序时,我得到以下响应: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Fri Sep 06 20:46:04 CEST 2019 There was an unexpected error (type=Internal Server Error, sta

在Spring工具套件中,应用程序运行良好

在浏览器中运行应用程序时,我得到以下响应:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Sep 06 20:46:04 CEST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No message available
localhost:8080,索引页非常好。如果我点击了调用“/getinfo”页面的按钮,那么“getTrades()”运行的原因是什么,我会得到这个白标签错误

我发现它在“public List getItemNamesandSfromTXT()函数”中的以下几行消失:

String content = "";
        try {
            content = new String(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            System.out.println("GetInfoService.java --> getItemNamesAndIDsFromTXT() --> content = new String(Files.readAllBytes(file.toPath())); --> " + e);
        }
这是我的(唯一)控制器:

@Controller
public class IndexController {

    @Autowired
    GetInfoService gis = new GetInfoService();

    @Autowired
    CalculateProfitService cp = new CalculateProfitService();


    @GetMapping("/")
    public String getIndex(Model model) {

        return "index";
    }


    @RequestMapping("/getinfo") 
    public String gotTheData(
            @RequestParam(name="fromCity") String fromCity, 
            @RequestParam(name="toCity") String toCity, 
            @RequestParam("profitMinimum") int profitMinimum, 
            @RequestParam("profitMaximum") int profitMaximum, 
            @RequestParam("auctionTax") int auctionTax, 
            Model model) {  


        model.addAttribute("trades", gis.getTrades(fromCity, toCity, profitMinimum, profitMaximum, auctionTax));    

        return "index";
    }
}
这是我的服务:

@Service
public class GetInfoService {

    public List<Item> getItemNamesAndIDsFromTXT() {

        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:ids");
        } catch (FileNotFoundException e) {
            System.out.println("GetInfoService.java --> getItemNamesAndIDsFromTXT() --> file = ResourceUtils.getFile(\"classpath:ids\"); --> " + e);
        }
        String content = "";
        try {
            content = new String(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            System.out.println("GetInfoService.java --> getItemNamesAndIDsFromTXT() --> content = new String(Files.readAllBytes(file.toPath())); --> " + e);
        }
        List<String> lines = Arrays.asList(content.split("\\n"));

        List<Item> items = new ArrayList<>();

        for (String i : lines) {
            String uniqueName = i.substring(i.indexOf(':') + 1, i.lastIndexOf(':')).trim();
            String tier = uniqueName.substring(0, 2);

            String itemName = i.substring(i.lastIndexOf(':') + 2).trim();
            if (uniqueName.contains("@")) {
                itemName = itemName + uniqueName.substring(uniqueName.indexOf('@'));
            }
            items.add(new Item(uniqueName, itemName, tier));

        }

        return items;
    }

    public ArrayList<Offer> getOffers(String fromCity, String toCity, int auctionTax) {
        final List<Item> items = getItemNamesAndIDsFromTXT();
        ArrayList<Offer> offers = new ArrayList<>();

        String firstPartOfUrl = "https://www.albion-online-data.com/api/v2/stats/prices/";
        String secondPartOfUrl = "";
        String thirdPartOfUrl = "?locations=";
        String fourthPartOfUrl = "";
        String fifthPartOfUrl = "&qualities=0";

        fourthPartOfUrl = fromCity + "," + toCity;
        //System.out.println(fourthPartOfUrl);

        String url = "";

        int n = 1;

        JSONFromURL jfu = new JSONFromURL();

        for (Item i : items) {
            secondPartOfUrl += i.getId() + ",";
            n++;

            if (n % 19 == 0 || (i.equals(items.get(items.size() - 1)))) {
                secondPartOfUrl = secondPartOfUrl.substring(0, secondPartOfUrl.length() - 1);
                url = firstPartOfUrl + secondPartOfUrl + thirdPartOfUrl + fourthPartOfUrl + fifthPartOfUrl;
                // System.out.println(url);
                JSONArray jsonarray = jfu.callMeOnArray(url);

                for (int j = 0; j < jsonarray.length(); j++) {
                    JSONObject obj = jsonarray.getJSONObject(j);
                    String itemID = obj.getString("item_id");

                    Item tempItem = items.stream().filter(e -> itemID.equals(e.getId())).findAny().orElse(null);

                    if (tempItem != null && obj.getInt("sell_price_min") > 0) {
                        String city = obj.getString("city");
                        int sellPriceMin = obj.getInt("sell_price_min");
                        if (toCity.contains(city)) sellPriceMin = (int) (sellPriceMin * (100 - auctionTax) / 100);
                        String sellPriceMinDate = obj.getString("sell_price_min_date");
                        int buyPriceMax = obj.getInt("buy_price_max");
                        String buyPriceMaxDate = obj.getString("buy_price_max_date");

                        offers.add(new Offer(tempItem, city, sellPriceMin, sellPriceMinDate, buyPriceMax,
                                buyPriceMaxDate));
                    }
                }

                secondPartOfUrl = "";

            }
        }

        // offers.stream().forEach(e -> System.out.println(e));

        return offers;

    }

    public List<Trade> getTrades(String fromCity, String toCity, int profitMinimum, int profitMaximum, int auctionTax)  {

     long start = System.currentTimeMillis();
        List<Trade> trades = new ArrayList<>();

        ArrayList<Offer> offers = new ArrayList<>();
        try {
            offers = getOffers(fromCity, toCity, auctionTax);
        } catch (JSONException e) {
            System.out.println("GetInfoService.java --> getTrades(String fromCity, String toCity, String profitInput, String profitMaximum) --> " + e);
        }

        if (fromCity.contains("FortSterling")) fromCity = fromCity.substring(0, fromCity.indexOf("Sterling")) + " " + fromCity.substring(fromCity.indexOf("Sterling"));
        if (  toCity.contains("FortSterling")) toCity   = toCity  .substring(0,   toCity.indexOf("Sterling")) + " " +   toCity.substring(toCity  .indexOf("Sterling"));


        final String fromCityFinal = fromCity;
        final String toCityFinal = toCity;

        List<Offer> fromOffers = offers.stream()
                .filter(e -> fromCityFinal.contains(e.getCity()))
                .collect(Collectors.toList());
        List<Offer> toOffers = offers.stream()
                .filter(e -> toCityFinal.contains(e.getCity()))
                .collect(Collectors.toList());

        for (int i = 0; i < fromOffers.size(); i++) {
            Offer fromOffer = fromOffers.get(i);

            for (int j = 0; j < toOffers.size(); j++) {
                Offer toOffer = toOffers.get(j);

                if (fromOffer.getItem().getId().equals(toOffer.getItem().getId())) {
                    if ((toOffer.getSellPriceMin() - fromOffer.getSellPriceMin() > profitMinimum) && (toOffer.getSellPriceMin() - fromOffer.getSellPriceMin() <= profitMaximum)) {
                        trades.add(new Trade(fromOffer, toOffer));
                    }
                }
            }

        }

        Collections.sort(trades);

        // trades.stream().forEach(e->System.out.println(e));

         long end = System.currentTimeMillis();

         System.out.println("It took " + (end-start) + " milliseconds!");

        return trades;
    }

谢谢

文件不在那里。字节在jar中,但不能从这样的路径加载。当在IDE中运行它时,该文件以该路径存在

InputStream是={CLASSNAMEHERE}.class.getClassLoader().getResourceAsStream(路径)

你可以得到字节,然后从那里变成字符串

public class ResourceToString {
public static void main(String[] args) {
    String pi  = convertStreamToString(ResourceToString.class.getClassLoader().getResourceAsStream("pi.txt"));
    System.out.println(pi);

}
private static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
}  

在本例中,pi.txt位于我的资源文件夹
\{projDir}\src\main\resources

多亏了mavriksc,我将方法改为:

public List<Item> getItemNamesAndIDsFromTXT() {

List<Item> items = new ArrayList<>();

String content =  convertStreamToString(TransportFromCityToCityApplication.class.getClassLoader().getResourceAsStream("ids"));

List<String> lines = Arrays.asList(content.split("\\n"));


for (String i : lines) {
    String uniqueName = i.substring(i.indexOf(':') + 1, i.lastIndexOf(':')).trim();
    String tier = uniqueName.substring(0, 2);

    String itemName = i.substring(i.lastIndexOf(':') + 2).trim();
    if (uniqueName.contains("@")) {
        itemName = itemName + uniqueName.substring(uniqueName.indexOf('@'));
    }
    items.add(new Item(uniqueName, itemName, tier));

}

return items;
}
public List getItemNamesandSfromTXT(){
List items=新建ArrayList();
字符串内容=convertStreamToString(TransportFromCityToCityApplication.class.getClassLoader().getResourceAsStream(“ids”);
列表行=数组.asList(content.split(\\n”);
用于(字符串i:行){
String uniqueName=i.substring(i.indexOf(':')+1,i.lastIndexOf(':')).trim();
String tier=uniqueName.substring(0,2);
String itemName=i.substring(i.lastIndexOf(':')+2.trim();
if(uniqueName.contains(“@”)){
itemName=itemName+uniqueName.substring(uniqueName.indexOf('@');
}
添加(新项目(uniqueName、itemName、tier));
}
退货项目;
}

它是有效的。因此,在我看来,如果您想在IDE之外使用您的应用程序,“类路径”方法不起作用。

堆栈跟踪在哪里?请检查控制台是否有任何错误?不知道如何检查控制台。我以jar开头。。。我没有打开任何东西。您的jar打印输出。还要注意,捕获异常然后只向stdout写入不是一个好习惯;它倾向于隐藏错误,在这种情况下,您只是在不一致的状态下继续。堆栈跟踪已经包含发生错误的类、方法和行号,通常最好让它转义并由Spring处理。最后,您的
新的
将受到影响。使用构造函数参数要好得多。我到底应该如何更改代码?我应该把这些代码放在哪里?我不知道类名,所以我不能确切地告诉你整个类的
请参阅在一分钟内编辑,但是在
getItemNames和dSfromTXT
中使用这些东西可以很好地工作。非常感谢。请注意,Spring很乐意为您注入一个
@值(“classpath:/pi.txt”)InputStream。
public class ResourceToString {
public static void main(String[] args) {
    String pi  = convertStreamToString(ResourceToString.class.getClassLoader().getResourceAsStream("pi.txt"));
    System.out.println(pi);

}
private static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
}  
public List<Item> getItemNamesAndIDsFromTXT() {

List<Item> items = new ArrayList<>();

String content =  convertStreamToString(TransportFromCityToCityApplication.class.getClassLoader().getResourceAsStream("ids"));

List<String> lines = Arrays.asList(content.split("\\n"));


for (String i : lines) {
    String uniqueName = i.substring(i.indexOf(':') + 1, i.lastIndexOf(':')).trim();
    String tier = uniqueName.substring(0, 2);

    String itemName = i.substring(i.lastIndexOf(':') + 2).trim();
    if (uniqueName.contains("@")) {
        itemName = itemName + uniqueName.substring(uniqueName.indexOf('@'));
    }
    items.add(new Item(uniqueName, itemName, tier));

}

return items;
}