java - 如何使用 FileReader 确保在 Java 中找到文件?
问题描述
我目前正在为学校编写一个 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");
}
}
}
解决方案
您的问题似乎是由于您在尝试读取文件时命名文件的方式与编写文件时不同。您尝试读取时使用的文件名是"./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));
...
希望这可以帮助。
推荐阅读
- macos - 如何将 openssl 静态链接到我的项目?(未定义的架构符号)
- python - 在使用 python 弹出的浏览器中单击复选框
- html - 如何将 CSS 着色应用到这个烧瓶模板?
- c# - 实体 Remove() 将外键属性设置为 null
- gtk - Gtk 绘图图形项目
- python - 在同步文件夹之外重新安装和使用 python3
- php - 使用没有框架的作曲家
- redis-cluster - redis sentinel 未将 SDOWN 升级为 ODOWN 事件
- opencv - OpenCv 为 cv2.matchTemplate 创建模板
- discord - 我不断收到此错误---- AttributeError:'NoneType'对象没有属性'stop'。我能做些什么?