简体   繁体   中英

When i run jar file i can't read files correctly

I wrote a code that creates cities and regions according to the regions of those cities by reading the information in the csv file. csv file is 81 lines long. It contains some information from 81 cities in Turkey. I want to add each line in this csv file to a String Array and then print it on the screen. I also want to keep the region objects that I created with this information in a Region array. Then, I want to print the region names from this region array. There are 7 regions in Turkey.

Edit: I tried to read data from txt file instead of csv. I get same error again. Also, I'm trying to run jar on Windows. I get these errors on windows(10), but when I try to run the program on ubuntu, I don't.

The code is looking work fine on Eclipse and it gives that output that I want.

output

I wanted to run this program with the executable jar file.So, I exported the project as runnable jar via Eclipse, but when I try to run this jar file on cmd,by typing:

java -jar myjar.jar

I get an error like this.

error

I don't know why I got this error. The CSV file is as follows.

CSV

When I run the program step by step with eclipse, I can't find anything that might cause an error. what do you think about this problem?

Where could I have made a mistake?

Here is my all class definitions.

main class

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());
        }

    }

}

array creator class

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;

    }

}

region class


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;
    }

}

city class


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;
    }

}

When I read data from the CSV file with BufferedReader instead of reading it with Scanner, my problem was resolved. Also, I used the necessary files (csv files) as embbedded-resource by putting them in the package named resource.

I used this for detecting capacity

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;

    }

instead of

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;
    }

And I used this code for creating info array

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;

    }

instead of

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;
    }

Finally, I called these methods in main like

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

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

Now, I can run my program without any problems by double clicking on the jar file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM