如何确保使用FileReader在Java中找到文件?

时间:2019-05-15 07:14:55

标签: java filewriter

我目前正在为学校编写DnD风格的程序,我正试图从文本文件中读取怪物和有关它们的数据。这需要通过这种方式完成,因此我选择使用FileReader。但是,尽管我尽了最大的努力,但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 个答案:

答案 0 :(得分:1)

似乎您的问题是由于尝试读取文件时与编写文件时对文件的命名不同。尝试读取时使用的文件名为 "./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));
...

希望这会有所帮助。

答案 1 :(得分:0)

以下说明将在当前工作目录中查找文件。

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