微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我运行 jar 文件时,我无法正确读取文件

如何解决当我运行 jar 文件时,我无法正确读取文件

我写了一个代码,通过读取csv文件中的信息,根据这些城市的地区创建城市和地区。 .csv 文件长 81 行。它包含来自土耳其 81 个城市的一些信息。我想将此 csv 文件中的每一行添加一个字符串数组中,然后将其打印在屏幕上。我还想将使用此信息创建的区域对象保留在 Region 数组中。然后,我想从这个区域数组中打印区域名称。土耳其有 7 个地区。

编辑:我尝试从 txt 文件而不是 csv 读取数据。我再次遇到同样的错误。另外,我正在尝试在 Windows 上运行 jar。我在 windows(10) 上遇到这些错误,但是当我尝试在 ubuntu 上运行该程序时,却没有。

代码在 Eclipse 上看起来运行良好,并提供了我想要的输出

output

我想用可执行的 jar 文件运行这个程序。所以,我通过 Eclipse 将项目导出为可运行的 jar,但是当我尝试在 cmd 上运行这个 jar 文件时,输入:

java -jar myjar.jar

我收到这样的错误

error

我不知道为什么会出现此错误。 CSV文件如下。

CSV

当我用eclipse逐步运行程序时,我找不到任何可能导致错误的东西。你怎么看这个问题?

我哪里出错了?

这是我所有的类定义

主类

import java.io.FileNotFoundException;

public class Launcher {

    public static void main(String[] args) throws FileNotFoundException {

        String[] infoArray = ArrayCreator.createInfoArray("Cities.csv");
        for (String info : infoArray) {
            System.out.println(info);
        }
        System.out.println();
        Region[] regionArray = ArrayCreator.createRegionArray(infoArray);
        for (Region region : regionArray) {
            System.out.println(region.getName());
        }

    }

}

数组创建类

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ArrayCreator {

    private static int capacityDetector(String fileName) throws FileNotFoundException {
        Scanner scanner1 = new Scanner(new File(fileName));
        int count = 0;
        while (scanner1.hasNext()) {
            count++;
            scanner1.nextLine();
        }
        scanner1.close();
        return count;
    }

    public static String[] createInfoArray(String fileName) throws FileNotFoundException {

        int capacity = capacityDetector(fileName);
        Scanner scanner2 = new Scanner(new File(fileName));
        String[] returnArray = new String[capacity];

        int index = 0;
        while (scanner2.hasNextLine()) {
            returnArray[index] = scanner2.nextLine();
            index++;
        }
        scanner2.close();
        return returnArray;
    }

    /**
     * This method creates an array which contains all the region.
     * 
     * @param infoArray String array about the cities and their regions information.
     *                  Elements must be in the CSV format and should be compatible
     *                  with other parts of the project.
     * @return an array which contains all the regions.
     */
    public static Region[] createRegionArray(String[] infoArray) {

        // infoArray is actually city information array. So there may be too many
        // times for the same region information. We just want to create only one region
        // for the same regions. So,we must do not create the regions that are already
        // exist.

        int index = 0;
        Region[] regionArr = new Region[index + 1];
        regionArr[index] = new Region(infoArray[0]); // We are sure that the region in the first information was not
                                                        // created before.
        for (int i = 1; i < infoArray.length; i++) {
            String info = infoArray[i];
            String[] splitted_info = info.split(",");
            boolean found = false;
            for (Region region : regionArr) {
                String newRegionName = splitted_info[3];
                String currRegionName = region.getName();

                if (newRegionName.equals(currRegionName)) {
                    found = true;
                    break;

                }
            }
            if (!found) { // if the object of this region was not created before.
                index++;
                Region new_region = new Region(info); // We dont kNow how many regions are there and we work with
                                                        // arrays. So we have to increase the array size manually.
                Region[] temp = new Region[index + 1];

                for (int j = 0; j < regionArr.length; j++) {
                    temp[j] = regionArr[j];
                }
                temp[index] = new_region;
                regionArr = temp;

            }
        }
        return regionArr;

    }

}

区域类


public class Region {
    private int ID;
    private String name;
    private City[] cities;

    /**
     * Constructor for Region Class Object.
     * 
     * @param name Name of the region.
     */
    public Region(String info) {
        String[] splitted_info = info.split(",");
        this.ID = Integer.parseInt(splitted_info[2]);
        this.name = splitted_info[3];

    }

    /**
     * A helper method to find the number of the cities which are in this region.
     * 
     * @param allCities An array which contains all the cities.
     * @return An integer which is the number of the cities in this region.
     *
     */
    private int findCitiesOfRegionArraySize(City[] allCities) {
        int returnInt = 0;
        for (City aCity : allCities) {
            if (aCity.getRegion().getName().equals(this.name)) {
                returnInt++;
            }
        }
        return returnInt;

    }

    /**
     * Creates the City array of a region.
     * 
     * @param allCities An array which contains all the cities.
     * @return City array that contains all the cities in this region.
     */
    public void createCitiesOfRegion(City[] allCities) {
        City[] cityArray = new City[findCitiesOfRegionArraySize(allCities)];
        int index = 0;
        for (City aCity : allCities) {
            if (aCity.getRegion().getName() == this.name) {
                cityArray[index] = aCity;
                index++;
            }
        }

        this.cities = cityArray;
    }

    public int getID() {
        return ID;
    }

    public String getName() {
        return name;
    }

    public City[] getCities() {
        return cities;
    }

}

城市类


public class Region {
    private int ID;
    private String name;
    private City[] cities;

    /**
     * Constructor for Region Class Object.
     * 
     * @param name Name of the region.
     */
    public Region(String info) {
        String[] splitted_info = info.split(",");
        this.ID = Integer.parseInt(splitted_info[2]);
        this.name = splitted_info[3];

    }

    /**
     * A helper method to find the number of the cities which are in this region.
     * 
     * @param allCities An array which contains all the cities.
     * @return An integer which is the number of the cities in this region.
     *
     */
    private int findCitiesOfRegionArraySize(City[] allCities) {
        int returnInt = 0;
        for (City aCity : allCities) {
            if (aCity.getRegion().getName().equals(this.name)) {
                returnInt++;
            }
        }
        return returnInt;

    }

    /**
     * Creates the City array of a region.
     * 
     * @param allCities An array which contains all the cities.
     * @return City array that contains all the cities in this region.
     */
    public void createCitiesOfRegion(City[] allCities) {
        City[] cityArray = new City[findCitiesOfRegionArraySize(allCities)];
        int index = 0;
        for (City aCity : allCities) {
            if (aCity.getRegion().getName() == this.name) {
                cityArray[index] = aCity;
                index++;
            }
        }

        this.cities = cityArray;
    }

    public int getID() {
        return ID;
    }

    public String getName() {
        return name;
    }

    public City[] getCities() {
        return cities;
    }

}

解决方法

当我使用 BufferedReader 从 CSV 文件读取数据而不是使用 Scanner 读取数据时,我的问题解决了。此外,我将必要的文件(csv 文件)用作嵌入资源,将它们放在名为资源的包中。

我用它来检测容量

private static int capacityDetector(String filename) throws IOException {
        InputStream in = new FileIO().getClass().getResourceAsStream(filename);
        @SuppressWarnings("resource")
        BufferedReader csv = new BufferedReader(new InputStreamReader(in,StandardCharsets.UTF_8));
        int capacity = 0;
        @SuppressWarnings("unused")
        String line;
        while ((line = csv.readLine()) != null) {
            capacity++;
        }
        return capacity;

    }

代替

private static int capacityDetector(String fileName) throws FileNotFoundException {
        Scanner scanner1 = new Scanner(new File(fileName));
        int count = 0;
        while (scanner1.hasNext()) {
            count++;
            scanner1.nextLine();
        }
        scanner1.close();
        return count;
    }

我用这段代码来创建信息数组

public static String[] createInfoArray(String filename) throws IOException {
        InputStream in = new FileIO().getClass().getResourceAsStream(filename);
        @SuppressWarnings("resource")
        BufferedReader csv = new BufferedReader(new InputStreamReader(in,StandardCharsets.UTF_8));
        int capacity = capacityDetector(filename);
        String[] infoArray = new String[capacity];
        for (int i = 0; i < capacity; i++) {
            infoArray[i] = csv.readLine();
        }
        return infoArray;

    }

代替

public static String[] createInfoArray(String fileName) throws FileNotFoundException {

        int capacity = capacityDetector(fileName);
        Scanner scanner2 = new Scanner(new File(fileName));
        String[] returnArray = new String[capacity];

        int index = 0;
        while (scanner2.hasNextLine()) {
            returnArray[index] = scanner2.nextLine();
            index++;
        }
        scanner2.close();
        return returnArray;
    }

最后,我在 main 中调用了这些方法

String[] cityInfoArray = FileIO.createInfoArray("/resources/Cities.csv");

String[] forecastInfoArray = FileIO.createInfoArray("/resources/WeeklyForecast.csv");

现在,我可以通过双击 jar 文件毫无问题地运行我的程序。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。