Как убедиться, что файл найден в Java с помощью FileReader? - PullRequest
1 голос
/ 15 мая 2019

В настоящее время я пишу программу в стиле DnD для школы и пытаюсь считывать монстров и данные о них из текстового файла.Это необходимо сделать таким образом, поэтому я решил использовать FileReader.Однако, несмотря на все мои попытки, FileReader не может найти путь к файлу, даже после того, как я пытаюсь создать его, если filereader не может его найти.

Я пытался разместить копии необходимого текстового файла на всем протяжениикаталоги, которые использует программа, однако я пока не вижу каких-либо изменений.

Я ожидаю, что программа чтения файлов найдет и установит ссылку на файл, однако она не сможет этого сделать.Я получаю ошибку Java.io.FileNotFoundException.(Я знаю, что я должен поймать это в попытке, будет сделано, как только я выясню это)

import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        // Main class variable declaration
        int menChoice;
        int numInElems = 3;
        int deaths = 0;
        String statRoll;
        Player player = new Player();
        Monster monster = new Monster();
        // Read in monster table
        /*File file = new File("monster_table");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        if (!file.exists()) {
            createMonsterFile();
            System.err.println(file.getAbsolutePath());
        }
        try {
            reader = new BufferedReader(new FileReader("monster_table.txt"));
            if (reader.readLine() != null) {
                System.out.println("Monster table successfully loaded.\n");
                clr();
            }
        } catch (IOException e) {
            System.out.println("That's a pretty dank error mate.\nSeems as if you can't read your monster table\ninto your program, or create it.\n\nOuch.\n" + e);
        }*/
        // Begin user interaction
        System.out.println("Hello, welcome to the DnD program.\nPlease select and option to continue.\n1: Start\n2: Quit\n\n");
        Scanner in = new Scanner(System.in);
        menChoice = in.nextInt();
        System.out.println("\n");
        while (menChoice != 1 && menChoice != 2) {
            System.out.println("Invalid input. Please only enter 1 or 2.\n");
            menChoice = in.nextInt();
            System.out.println("\n");
        }
        if (menChoice == 1) {
            // If i had time i could like, be super cool and make a function for this, but that's for fuckin nerds lmfao
            System.out.println("Please pick a class.\n1. Barbarian\n2. Bard\n3. Druid\n4. Monk\n5. Paladin\n6. Rogue\n7. Warlock\n8. Wizard\n\n");
            String[] classes = {"Barbarian", "Bard", "Druid", "Monk", "Paladin", "Rogue", "Warlock", "Wizard"};
            menChoice = in.nextInt();
            while (menChoice < 1 || menChoice > 8) {
                System.out.println("Invalid input. Please only enter a valid choice.\n");
                menChoice = in.nextInt();
                System.out.println("\n");
            }
            player.setPlayerClass(classes[menChoice - 1]);
            System.out.println("Please pick a race.\n1. Dwarf\n2. Elf\n3. Gnome\n4. Halfling\n5. Human\n\n");
            String[] races = {"Dwarf", "Elf", "Gnome", "Halfling", "Human"};
            menChoice = in.nextInt();
            while (menChoice < 1 || menChoice > 5) {
                System.out.println("Invalid input. Please only enter a valid choice.\n");
                menChoice = in.nextInt();
                System.out.println("\n");
            }
            player.setRace(races[menChoice - 1]);
            System.out.println("Please pick a profession.\n1. Herbalist\n2. Alchemist\n3. Blacksmith\n4. Soldier\n5. Hunter\n6. Gambler\n\n");
            String[] professions = {"Herbalist", "Alchemist", "Blacksmith", "Soldier", "Hunter", "Gambler"};
            menChoice = in.nextInt();
            while (menChoice < 1 || menChoice > 6) {
                System.out.println("Invalid input. Please only enter a valid choice.\n");
                menChoice = in.nextInt();
                System.out.println("\n");
            }
            player.setProfession(professions[menChoice - 1]);
            // R A N D O M R O L L I N G  > * B E G I N ! *
            do {
                System.out.println("Rolling stats!");
                player.setSTR(ThreadLocalRandom.current().nextInt(3, 18 + 1));
                player.setINT(ThreadLocalRandom.current().nextInt(3, 18 + 1));
                player.setWIS(ThreadLocalRandom.current().nextInt(3, 18 + 1));
                player.setCON(ThreadLocalRandom.current().nextInt(3, 18 + 1));
                player.setDEX(ThreadLocalRandom.current().nextInt(3, 18 + 1));
                player.setCHR(ThreadLocalRandom.current().nextInt(3, 18 + 1));
                System.out.println("STR: " + player.getSTR() + "\n" + "INT: " + player.getINT() + "\n" + "WIS: " + player.getWIS() + "\n" + "CON: " + player.getCON() + "\n" + "DEX: " + player.getDEX() + "\n" + "CHR: " + player.getCHR() + "\n" + "Are you happy with this roll?\n(y/n)");
                statRoll = in.nextLine();
                while (!statRoll.equals("n") && !statRoll.equals("N") && !statRoll.equals("y") && !statRoll.equals("Y")) {
                    System.out.println("Invalid input. Please only respond with (y/n).\n");
                    statRoll = in.nextLine();
                    System.out.println("\n");
                }
            } while (statRoll.equals("n") || statRoll.equals("N"));
            System.out.println("\n");
            player.setHealth(player.getSTR() + 10);
            System.out.println("Your character has been created.\nIt is time to move forward to combat!\n\n");
            // Combat will begin here.
            while (player.getLevel() < 2) {
                File file = new File("./monster_table.txt");
                FileReader reader = new FileReader("./monster_table.txt");
                if (!file.exists()) {
                    createMonsterFile();
                    System.err.println(file.getAbsolutePath());
                }
                try {
                    if (reader.readLine() != null) {
                        System.out.println("Monster table successfully loaded.\n");
                        clr();
                    }
                } catch (IOException e) {
                    System.out.println("That's a pretty dank error mate.\nSeems as if you can't read your monster table\ninto your program, or create it.\n\nOuch.\n" + e);
                }
                player.setHealth(player.getSTR() + 10);
                if (deaths > 0) {
                    System.out.println("You awake in a nearby town, and on your way back to your party, you encounter another beast.");
                }
                int importNum = (int)(Math.floor(Math.random() * 11) + 1);
                if (importNum > 11) {
                    importNum = 11;
                } else if (importNum == 1) {
                    importNum = 2;
                }
                for (int i = 1; i < importNum; i++) {
                    reader.readLine();
                }
                String selectedMonster = reader.readLine();
                String[] monsterImport = selectedMonster.split(" ");
                if (monsterImport.length > numInElems) {
                    monsterImport[0] = (monsterImport[0] + " " + monsterImport[1]);
                    monsterImport[1] = monsterImport[2];
                    monsterImport[2] = monsterImport[3];
                    monster.setName(monsterImport[0]);
                    monster.setHealth(Integer.parseInt(monsterImport[1]));
                    monster.setDamage(Integer.parseInt(monsterImport[2]));
                }
                else {
                    monster.setName(monsterImport[0]);
                    monster.setHealth(Integer.parseInt(monsterImport[1]));
                    monster.setDamage(Integer.parseInt(monsterImport[2]));
                }
                while (player.getHealth() > 0 && monster.getHealth() > 0) {
                    System.out.println("You are at " + player.getHealth() + ". Your opponent, " + monster.getName() + ", is at " + monster.getHealth() + ".\nWhat will you do?\n1. Fight\n2. Run");
                    menChoice = in.nextInt();
                    while (menChoice != 1 && menChoice != 2) {
                        System.out.println("Invalid input. Please only enter 1 or 2.\n");
                        menChoice = in.nextInt();
                        System.out.println("\n");
                    }
                    if (menChoice == 1) {
                        int RNG = (int)Math.floor(Math.random() * 4);
                        int monsterRNG = (int)Math.floor(Math.random() * 4);
                        if (RNG == 1 || RNG == 2 || RNG == 3) {
                            monster.setHealth(monster.getHealth() - player.getDamage());
                            System.out.println("You dealt " + player.getDamage() + " damage to " + monster.getName() + "!");
                            if (monster.getHealth() <= 0) {
                                player.setExp(player.getExp() + 5);
                                if (player.getExp() > (player.getSTR() + 10) * 50) {
                                    player.setLevel(player.getLevel() + 1);
                                }
                            }
                        } else {
                            System.out.println("You missed!");
                        }
                        if (monsterRNG == 1) {
                            player.setHealth(player.getHealth() - monster.getDamage());
                            System.out.println("The monster dealt " + monster.getDamage() + " to you!");
                        } else {
                            System.out.println("The monster missed.");
                        }
                    } else {
                        int prayToRNGesus = (int)Math.floor(Math.random() * 4);
                        if (prayToRNGesus == 1) {
                            monster.setHealth(0);
                            System.out.println("You have successfully fled.\n");
                        } else {
                            player.setHealth(0);
                            System.out.println("In your attempts to flee, you were slain.");
                            player.setExp(player.getExp() - 10);
                            deaths++;
                        }
                    }

                }
            }
            System.out.println("Congratulations on making it to level 2!\nDo you wish to save your character?\n1. Yes\n2. No");
            menChoice = in.nextInt();
            while (menChoice != 1 && menChoice != 2) {
                System.out.println("Invalid input. Please only enter 1 or 2.\n");
                menChoice = in.nextInt();
                System.out.println("\n");
            }
            if (menChoice == 1) {
                System.out.println("Excellent! Please name your character.");
                String name = in.nextLine();
                player.setName(name);
                System.out.println("Saving your character...");
                BufferedWriter writer;
                int i = 1;
                File outFile = new File("./character" + String.valueOf(i) + ".txt");
                while (outFile.exists() && i < 3) {
                    i++;
                    outFile = new File("./character" + String.valueOf(i) + ".txt");
                }
                try {
                    writer = new BufferedWriter(new FileWriter(outFile));
                    writer.write("Name: " + player.getName());
                    writer.newLine();
                    writer.write("Race: " + player.getRace());
                    writer.newLine();
                    writer.write("Profession: " + player.getProfession());
                    writer.newLine();
                    writer.write("Class: " + player.getPlayerClass());
                    writer.newLine();
                    writer.write("INT: " + String.valueOf(player.getINT()));
                    writer.newLine();
                    writer.write("STR: " + String.valueOf(player.getSTR()));
                    writer.newLine();
                    writer.write("WIS: " + String.valueOf(player.getWIS()));
                    writer.newLine();
                    writer.write("CON: " + String.valueOf(player.getCON()));
                    writer.newLine();
                    writer.write("DEX: " + String.valueOf(player.getDEX()));
                    writer.newLine();
                    writer.write("CHR: " + String.valueOf(player.getCHR()));
                    writer.newLine();
                    writer.flush();
                    writer.close();
                } catch(IOException e) {
                    System.out.println("IO error. " + e);
                }
            }

        } else if (menChoice == 2) {
            System.exit(0);
        } else {
            System.out.println("User input validation error.\n");
        }
    }

    private static void createMonsterFile() {
        File monsterFile = new File("./monster_table.txt");
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new FileWriter(monsterFile));
            writer.write("MonsterName HitPoints HitDamage\nHydra 50 6\nCyclops 20 1\nGiant Snake 5 1\nPhred 100 5\nPurple Monkey 10 2\nIce Golem 25 10\nHeat Miser 50 2\nSquirrel 2 5\nWhite Whale 80 4\nSmurf 5 2");
            writer.flush();
            System.out.println("Monster table successfully loaded.\n");
            clr();
        } catch (IOException e) {
            System.out.println("That's a pretty dank error mate.\nSeems as if you can't write your monster table.\n\nOuch.\n" + e);
        }
    }

    static void clr() {
        for (int i = 0; i < 50; i++) {
            System.out.println("\n");
        }
    }
}

Ответы [ 2 ]

1 голос
/ 15 мая 2019

Кажется, что ваша проблема в том, что при попытке прочитать файл по-другому, когда вы пытаетесь его прочитать, чем когда вы его написали.Имя файла, которое вы используете при попытке прочитать, равно "./monster_file":

...
        file = new File("./monster_file");
        FileReader reader = new FileReader(file);
...

, а имя файла, который вы фактически написали, - "./monster_table.txt":

...
        File file = new File("./monster_table.txt");
        if (!file.exists()) {
            createMonsterFile();
        }

...

    private static void createMonsterFile() {
        File monsterFile = new File("./monster_table.txt");
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new FileWriter(monsterFile));
...

Надеюсь, это поможет.

0 голосов
/ 15 мая 2019

Следующая инструкция будет искать файл в текущем рабочем каталоге.

file = new File("./monster_file");

Рабочий каталог зависит от того, как вы вызываете ваше Java-приложение.

Лучше всего в этом случае выдать сообщение об ошибке, в котором, например, четко указано, что вы ищете и где.

        File file = new File("./monster_file");
        if(!file.exists()){
            System.err.println("I can't find "+file.getAbsolutePath());
        }

Помните также, что вы ищете файл без расширения , и, возможно, вместо этого у вас есть файл с расширением . Возможно, вы пытаетесь открыть monster_file, но в вашем каталоге у вас есть monster_file.txt.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...