Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: File Input and Output and Exception Handling

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default File Input and Output and Exception Handling

    Okay, so I have a project due in a friday and my Nana passed away this morning so I really have to work at double speed to get it in for friday seeing as I will have funeral and such in the coming days.

    With my code, I was wondering how to implement a File Input and Output system with exception handling into my current program.

    The current program is used for making arraylists of a Hero Character, you can add a Hero with a name, age, attack and defense points.

    The main thing I need to do now is just do some fileIO to allow for the information to be saved to a file...
    Thanks in advance <3

    package myHero;
     
    /*The aim of this project is to allow the user to input data which will give structure to a character known as HERO. 
     There can be several Heroes, more can be added using the create a Hero method.*/
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;
     
    //Creates a class with the Scanner for user input and also declares the ArrayLists for each element of the Hero we are to create.
    public class HeroCreate {
     
        Scanner input = new Scanner(System.in);
        //Elements of the Hero such as Name, Attack and Defense. 
        List<String> hName = new ArrayList<>();
        List<Integer> hAge = new ArrayList<>();
        List<String> hRace = new ArrayList<>();
        List<Integer> hAttack = new ArrayList<>();
        List<Integer> hDefense = new ArrayList<>();
     
    //This acts as the HUB for the user to enter in a number to choose from the options in the list.
        public void StartPanel() {
            System.out.println("\n" + "WELCOME TO HERO CREATOR!");
            System.out.println("1. Create a Hero Now!");
            System.out.println("2. Delete An Existing Hero?");
            System.out.println("3. Show Current Heroes!");
            System.out.println("4. Exit Menu ");
     
            //This is where the program identifies which number the user has chosen and links them to the next method.
            int choice = input.nextInt();
     
            if (choice == 1) {
                CreateHero();
            } else if (choice == 2) {
                DeleteHero();
                ShowTeam();
            } else if (choice == 3) {
                ShowTeam();
                StartPanel();
            } else if (choice == 4) {
                StopPro();
            } else {
                System.out.println("Error!");
                StartPanel();
            }
     
        }
     
    //This is class which allows for the user to create the HERO, giving it all of its details. 
    //When the user enters the details it is stored in an array corresponding to its role. i.e NAME in the hName arrayList.
        public void CreateHero() {
            System.out.print("Name Your Hero: ");
            input.nextLine();
            String newHeroName = input.nextLine();
            hName.add(newHeroName);
     
            System.out.print("How Old Is Your Hero?: ");
            int newHeroAge = input.nextInt();
            hAge.add(newHeroAge);
     
            System.out.print("Which Race is your Hero?: ");
            input.nextLine();
            String newHeroRace = input.nextLine();
            hRace.add(newHeroRace);
     
    //The following assigns random values between 1 and 100 to the Attack and Defense element of the HERO.
            int min = 0;
            int max = 100;
            Random r = new Random();
     
            int newHeroAtt = r.nextInt(max - min + 1) + min;
            hAttack.add(newHeroAtt);
     
            int newHeroDef = r.nextInt(max - min + 1) + min;
            hDefense.add(newHeroDef);
     
     
    //A println to declare a character has been added.
            System.out.println("\n" + "The Hero " + hName.get(hName.size() - 1) + " Was Added!" + "\n");
     
    //A choice to continue creating Heroes or to return to the main menu.
            System.out.println("Add Another Hero?");
            System.out.println("1. Create Another Hero!");
            System.out.println("2. Return to Main Menu.");
     
            int choice = input.nextInt();
     
            if (choice == 1) {
                CreateHero();
            } else if (choice == 2) {
                StartPanel();
            }
        }
     
    //This method allows for a Hero to be deleted for whatever reason, by removing the elements of a Hero and deleting it from the arrayList.
        public void DeleteHero() {
            ShowTeam();
            System.out.println(" Which Hero Will Be Deleted? (1 to " + hName.size() + ")");
            int delete = input.nextInt();
            if (delete > hName.size()) {
                System.out.println("That is not a choice!");
                StartPanel();
            } else {
                delete--;
                System.out.println("Would you like to delete the following hero?: " + hName.get(delete));
                System.out.print("1 for YES or 2 for NO" + "\n");
                int confirmDelete = input.nextInt();
                if (confirmDelete == 1) {
                    hName.remove(delete);
                    hAge.remove(delete);
                    hRace.remove(delete);
                    hAttack.remove(delete);
                    hDefense.remove(delete);
                    System.out.println("Hero has been deleted!");
                    StartPanel();
                } else {
                    StartPanel();
                }
     
            }
        }
     
    //This is a useful method which allows the user to view all current Hero characters in the ArrayList.
        public void ShowTeam() {
            System.out.println("\n");
            for (int i = 0; i < hName.size(); i++) {
                int counter = i + 1;
                System.out.println("H E R O   " + counter);
                System.out.println("-------------------------");
                System.out.println("Name: " + hName.get(i) + "\n" + " Age: " + hAge.get(i) + "\n" + " Race: " + hRace.get(i) + "\n" + " Attack: " + hAttack.get(i) + "\n" + " Defense: " + hDefense.get(i) + "\n" + "\n");
            }
        }
     
    //This stops the program from running.
        static void StopPro() {
            System.out.println("Ended");
            System.exit(0);
        }
    }
     
    //This is the main body which envokes the program
    class Hero {
     
        public static void main(String[] args) {
     
            HeroCreate heroChar = new HeroCreate();
     
            heroChar.StartPanel();
        }
    }
    Last edited by Norm; January 15th, 2013 at 07:46 AM. Reason: Change quote to code tags


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    do some fileIO to allow for the information to be saved to a file...
    What data do you want to save? What format do you want to save it in? As text or ???

    When and where in the program do you want to create the file and write data to it?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    I want to save the data I have entered into the arraylist into a text file, so I would probably create the file at the start? then go through the program and enter the details of the characters in the array and then when I save the character for its information to be added to the text file.

    Also thank you for the reply <3

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    Next, what will go on each line in the file?
    Will data from one execution be appended to data from an earlier execution of the program?

    When will the file be read? What will its contents be used for?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    On each line would be something like this...
    The user must enter a Name, Race, Age, Attack and Defense.

    So there for each line would be...

    Name:
    Race:
    Age:
    Attack:
    Defense:

    and then skip a line and if another hero is added it will add their details too.

    The file should probably be read when the user wants to so maybe by adding another choice onto the list of options I have in my program.
    I don't really understand what you mean by what would they be used for? Sorry.

    It is just to store a Team of Heroes created by the user.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    Now try writing a small simple program that creates a file, writes out a few lines, closes the file and then reads them back and prints them. This is to learn how to use the classes and methods without the other code getting in the way and making things more complicated.

    what you mean by what would they be used for
    Who or what will read the file and use the data in it?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: File Input and Output and Exception Handling

    If you intend to use the latest NIO code in Java 7, then these are the very basics:

    Starting with the file path ...

    //create a path for the file you intend to use. This one uses the name 'my_file.txt' and the default directory for the project. So if you use Eclipse, it will be the .../workspace/your_project directory.

    Path p = Paths.get("my_file.txt");

    Alternatively you could also point the path to your 'home' directory for your particular system (eg. on my Windows 7 PC this will be c:/users/Starstreak)

    Path p = Paths.get(System.getProperty("user.home"), "my_file.txt");

  8. #8
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Okay, so I made a program where I use a pre made text file and then it prints its contents to the screen and creates a new text file...
    But I still don't really understand it.
    How am I supposed to combine this with my other program to achieve my goal?
    package HeroCreation;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;

    public class FileIO {

    public String readTextFile(String fileName) {
    String returnValue = "";
    FileReader file = null;
    String line = "";
    try {
    file = new FileReader(fileName);
    BufferedReader reader = new BufferedReader(file);
    while ((line = reader.readLine()) != null) {
    returnValue += line + "\n";
    }
    } catch (FileNotFoundException e) {
    throw new RuntimeException("File not found");
    } catch (IOException e) {
    throw new RuntimeException("IO Error occured");
    } finally {
    if (file != null) {
    try {
    file.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return returnValue;
    }

    public void writeTextFile(String fileName, String s) {
    FileWriter output = null;
    try {
    output = new FileWriter(fileName);
    BufferedWriter writer = new BufferedWriter(output);
    writer.write(s);
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (output != null) {
    try {
    output.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }


    }
    }

    package HeroCreation;
    public class Main {
    public static void main(String[] args) {
    FileIO myFile = new FileIO();
    String input = myFile.readTextFile("Testing.txt");
    System.out.println(input);
    myFile.writeTextFile("Testing2.txt", input);
    }
    }

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    Please use code tags to surround the code, note quote tags.

    But I still don't really understand it.
    What part of the code are you having problems with?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Quote Originally Posted by Norm View Post
    Please use code tags to surround the code, note quote tags.


    What part of the code are you having problems with?
    Sorry about that! I just don't know how to implement it in the original code to get it to work? Is that code sufficient to get the program working the way I want, how else do I add onto it?

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    get the program working the way I want
    Please explain what you want.
    You have posted code that you've written that writes lines to a file so you know how to create a file and write lines to it. Take the logic from the code in post#8 and put it into the program at the places where you want to create the file and where you want to write data to the file.


    Please use code tags to surround the code, not quote tags.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: File Input and Output and Exception Handling

    You have a few lines of data that relates to one 'Hero'.

    You can create a series of seperate methods to write the information to file. Say, one for reading, one for writing ...

    Things to consider:

    To use NIO2 or the older Java API.

    Code to check if the file exists and is writeable.

    Code to create the file.

    Whether to store data in a fresh file, one for each person?
    or
    Add the record to one big file? You would then have to think of how to extract/amend/delete specific lines.

  13. #13
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Okay, so I have been working on the code, it now requests user input on what option you want to choose, if you choose "add hero" option, a prompt comes up to enter a name, then an age then a race. When done, there is a println saying Hero added and then a description on the hero "Hero "Name" was added who is "age" years old and of the "race" race." This bit of information is saved to the binary.dat file decalred at the start and when you add another hero this line aswell as the new hero created line will come up. This is too saved in the binary.dat file...

    So my question is, how do I read the file at the start to ADD to the file even after the program is closed, so I can edit the contents whenever.

    package myHero;
     
    /*The aim of this project is to allow the user to input data which will give structure to a character known as HERO. 
     There can be several Heroes, more can be added using the create a Hero method.*/
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.EOFException;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;
     
    //Creates a class with the Scanner for user input and also declares the ArrayLists for each element of the Hero we are to create.
    public class HeroCreate {
     
        DataOutputStream outFile;
        DataInputStream inFile;
        String datafile = "binarydata.dat";
        Scanner input = new Scanner(System.in);
        //Elements of the Hero such as Name, Attack and Defense. 
        List<String> hName = new ArrayList<>();
        List<Integer> hAge = new ArrayList<>();
        List<String> hRace = new ArrayList<>();
        List<Integer> hAttack = new ArrayList<>();
        List<Integer> hDefense = new ArrayList<>();
     
    //This acts as the HUB for the user to enter in a number to choose from the options in the list.
        public void StartPanel() throws IOException {
            System.out.println("\n" + "WELCOME TO HERO CREATOR!");
            System.out.println("1. Create a Hero Now!");
            System.out.println("2. Delete An Existing Hero?");
            System.out.println("3. Show Current Heroes!");
            System.out.println("4. Exit Menu ");
     
            //This is where the program identifies which number the user has chosen and links them to the next method.
            int choice = input.nextInt();
     
            if (choice == 1) {
                CreateHero();
            } else if (choice == 2) {
                DeleteHero();
                ShowTeam();
            } else if (choice == 3) {
                ShowTeam();
                StartPanel();
            } else if (choice == 4) {
                StopPro();
            } else {
                System.out.println("Error!");
                StartPanel();
            }
     
     
     
        }
     
    //This is class which allows for the user to create the HERO, giving it all of its details. 
    //When the user enters the details it is stored in an array corresponding to its role. i.e NAME in the hName arrayList.
        public void CreateHero() throws IOException {
            System.out.print("Name Your Hero: ");
            input.nextLine();
            String newHeroName = input.nextLine();
            hName.add(newHeroName);
     
            System.out.print("How Old Is Your Hero?: ");
            int newHeroAge = input.nextInt();
            hAge.add(newHeroAge);
     
            System.out.print("Which Race is your Hero?: ");
            input.nextLine();
            String newHeroRace = input.nextLine();
            hRace.add(newHeroRace);
     
    //The following assigns random values between 1 and 100 to the Attack and Defense element of the HERO.
            int min = 0;
            int max = 100;
            Random r = new Random();
     
            int newHeroAtt = r.nextInt(max - min + 1) + min;
            hAttack.add(newHeroAtt);
     
            int newHeroDef = r.nextInt(max - min + 1) + min;
            hDefense.add(newHeroDef);
     
     
    //A println to declare a character has been added.
            System.out.println("\n" + "The Hero " + hName.get(hName.size() - 1) + " Was Added!" + "\n");
     
            try {
     
                outFile = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(datafile)));
     
                for (int x = 0; x < hName.size(); x++) {
                    outFile.writeUTF(hName.get(x));
                    outFile.writeInt(hAge.get(x));
                    outFile.writeUTF(hRace.get(x));
                    outFile.writeInt(hAttack.get(x));
                    outFile.writeInt(hDefense.get(x));
                }
                outFile.close();
            } catch (FileNotFoundException fnf) {
                System.out.println("Error! The File " + datafile + " cannot be located.");
            } catch (IOException ioe) {
                System.out.println("Error! An IO Excpetion has happened.");
            }
     
            try {
                inFile = new DataInputStream(new BufferedInputStream(new FileInputStream(datafile)));
     
     
                String tempName = "";
                String tempRace = "";
                int tempAge = 0;
                int tempAttack = 0;
                int tempDefense = 0;
     
                while (true) {
                    tempName = inFile.readUTF();
                    tempAge = inFile.readInt();
                    tempRace = inFile.readUTF();
                    tempAttack = inFile.readInt();
                    tempDefense = inFile.readInt();
                    System.out.format("The Hero %s is %d years old and is of the %s race, with an attack of %d and a defense of %d.%n", tempName, tempAge, tempRace, tempAttack, tempDefense);
                }
            } catch (FileNotFoundException fnf) {
                System.out.println("Error! The file " + datafile + "cannot be located.");
            } catch (EOFException e) {
                System.out.format("%nFile Successfully Updated!%n");
     
     
     
            }
     
     
     
     
    //A choice to continue creating Heroes or to return to the main menu.
            System.out.println("Add Another Hero?");
            System.out.println("1. Create Another Hero!");
            System.out.println("2. Return to Main Menu.");
     
            int choice = input.nextInt();
     
            if (choice == 1) {
                CreateHero();
            } else if (choice == 2) {
                StartPanel();
            }
        }
     
    //This method allows for a Hero to be deleted for whatever reason, by removing the elements of a Hero and deleting it from the arrayList.
        public void DeleteHero() throws IOException {
            ShowTeam();
            System.out.println(" Which Hero Will Be Deleted? (1 to " + hName.size() + ")");
            int delete = input.nextInt();
            if (delete > hName.size()) {
                System.out.println("That is not a choice!");
                StartPanel();
            } else {
                delete--;
                System.out.println("Would you like to delete the following hero?: " + hName.get(delete));
                System.out.print("1 for YES or 2 for NO" + "\n");
                int confirmDelete = input.nextInt();
                if (confirmDelete == 1) {
                    hName.remove(delete);
                    hAge.remove(delete);
                    hRace.remove(delete);
                    hAttack.remove(delete);
                    hDefense.remove(delete);
                    System.out.println("Hero has been deleted!");
                    StartPanel();
                } else {
                    StartPanel();
                }
     
            }
        }
     
    //This is a useful method which allows the user to view all current Hero characters in the ArrayList.
        public void ShowTeam() {
            System.out.println("\n");
            for (int i = 0; i < hName.size(); i++) {
                int counter = i + 1;
                System.out.println("H E R O   " + counter);
                System.out.println("-------------------------");
                System.out.println("Name: " + hName.get(i) + "\n" + " Age: " + hAge.get(i) + "\n" + " Race: " + hRace.get(i) + "\n" + " Attack: " + hAttack.get(i) + "\n" + " Defense: " + hDefense.get(i) + "\n" + "\n");
            }
        }
     
    //This stops the program from running.
        static void StopPro() {
            System.out.println("Ended");
            System.exit(0);
        }
    }
     
    //This is the main body which envokes the program
    class Hero {
     
        public static void main(String[] args) throws IOException {
     
            HeroCreate heroChar = new HeroCreate();
     
            heroChar.StartPanel();
        }
    }

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    how do I read the file at the start
    There was code in post#8 that reads lines from the file.

    What do you want to do with the lines you read from the file?

    after the program is closed,
    The program can't do anything after it is closed.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Hi, So I have been working on the project more, it is due tommorow at 12 noon.
    One final question I think, My code reads the information put in by the user which is in seperate arraylists, such as an array list for the names, array lists for the ages and so on.
    The information is saved to a binary file at the end of the program, now for my question.
    How do I read in the information from the file upon starting back up the program, like my program cant access the information I have stored previously, It can read back the data IN THE file as text but cant access them in a way such as...

    One of my choices is "view heroes" but when I choose it, it acts as though there are no objects in the array?

    package myHero;
     
    /*The aim of this project is to allow the user to input data which will give structure to a character known as HERO. 
     There can be several Heroes, more can be added using the create a Hero method.*/
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.EOFException;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;
     
    //Creates a class with the Scanner for user input and also declares the ArrayLists for each element of the Hero we are to create.
    public class HeroCreate {
     
     
     
        DataOutputStream outFile;
        DataInputStream inFile;
        String datafile = "binarydata.dat";
        Scanner input = new Scanner(System.in);
        //Elements of the Hero such as Name, Attack and Defense. 
        List<String> hName = new ArrayList<>();
        List<Integer> hAge = new ArrayList<>();
        List<String> hRace = new ArrayList<>();
        List<Integer> hAttack = new ArrayList<>();
        List<Integer> hDefense = new ArrayList<>();
     
    //This acts as the HUB for the user to enter in a number to choose from the options in the list.
        public void StartPanel() throws IOException {
            System.out.println("\n" + "WELCOME TO HERO CREATOR!");
            System.out.println("1. Create a Hero Now!");
            System.out.println("2. Delete An Existing Hero?");
            System.out.println("3. Show Current Heroes!");
            System.out.println("4. Exit Menu ");
     
            //This is where the program identifies which number the user has chosen and links them to the next method.
            int choice = input.nextInt();
     
            if (choice == 1) {
                CreateHero();
            } else if (choice == 2) {
                DeleteHero();
                ShowTeam();
            } else if (choice == 3) {
                ShowTeam();
                StartPanel();
            } else if (choice == 4) {
                StopPro();
            } else {
                System.out.println("Error!");
                StartPanel();
            }
     
     
     
        }
     
    //This is class which allows for the user to create the HERO, giving it all of its details. 
    //When the user enters the details it is stored in an array corresponding to its role. i.e NAME in the hName arrayList.
        public void CreateHero() throws IOException {
            System.out.print("Name Your Hero: ");
            input.nextLine();
            String newHeroName = input.nextLine();
            hName.add(newHeroName);
     
            System.out.print("How Old Is Your Hero?: ");
            int newHeroAge = input.nextInt();
            hAge.add(newHeroAge);
     
            System.out.print("Which Race is your Hero?: ");
            input.nextLine();
            String newHeroRace = input.nextLine();
            hRace.add(newHeroRace);
     
    //The following assigns random values between 1 and 100 to the Attack and Defense element of the HERO.
            int min = 0;
            int max = 100;
            Random r = new Random();
     
            int newHeroAtt = r.nextInt(max - min + 1) + min;
            hAttack.add(newHeroAtt);
     
            int newHeroDef = r.nextInt(max - min + 1) + min;
            hDefense.add(newHeroDef);
     
     
    //A println to declare a character has been added.
            System.out.println("\n" + "The Hero " + hName.get(hName.size() - 1) + " Was Added!" + "\n");
     
            try {
     
                outFile = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(datafile)));
     
                for (int x = 0; x < hName.size(); x++) {
                    outFile.writeUTF(hName.get(x));
                    outFile.writeInt(hAge.get(x));
                    outFile.writeUTF(hRace.get(x));
                    outFile.writeInt(hAttack.get(x));
                    outFile.writeInt(hDefense.get(x));
                }
                outFile.close();
            } catch (FileNotFoundException fnf) {
                System.out.println("Error! The File " + datafile + " cannot be located.");
            } catch (IOException ioe) {
                System.out.println("Error! An IO Excpetion has happened.");
            }
     
            try {
                inFile = new DataInputStream(new BufferedInputStream(new FileInputStream(datafile)));
     
     
                String tempName = "";
                String tempRace = "";
                int tempAge = 0;
                int tempAttack = 0;
                int tempDefense = 0;
     
                while (true) {
                    tempName = inFile.readUTF();
                    tempAge = inFile.readInt();
                    tempRace = inFile.readUTF();
                    tempAttack = inFile.readInt();
                    tempDefense = inFile.readInt();
                    System.out.format("The Hero %s is %d years old and is of the %s race, with an attack of %d and a defense of %d.%n", tempName, tempAge, tempRace, tempAttack, tempDefense);
                }
            } catch (FileNotFoundException fnf) {
                System.out.println("Error! The file " + datafile + "cannot be located.");
            } catch (EOFException e) {
                System.out.format("%nFile Successfully Updated!%n");
     
     
     
            }
     
     
     
     
    //A choice to continue creating Heroes or to return to the main menu.
            System.out.println("Add Another Hero?");
            System.out.println("1. Create Another Hero!");
            System.out.println("2. Return to Main Menu.");
     
            int choice = input.nextInt();
     
            if (choice == 1) {
                CreateHero();
            } else if (choice == 2) {
                StartPanel();
            }
        }
     
    //This method allows for a Hero to be deleted for whatever reason, by removing the elements of a Hero and deleting it from the arrayList.
        public void DeleteHero() throws IOException {
            ShowTeam();
            System.out.println(" Which Hero Will Be Deleted? (1 to " + hName.size() + ")");
            int delete = input.nextInt();
            if (delete > hName.size()) {
                System.out.println("That is not a choice!");
                StartPanel();
            } else {
                delete--;
                System.out.println("Would you like to delete the following hero?: " + hName.get(delete));
                System.out.print("1 for YES or 2 for NO" + "\n");
                int confirmDelete = input.nextInt();
                if (confirmDelete == 1) {
                    hName.remove(delete);
                    hAge.remove(delete);
                    hRace.remove(delete);
                    hAttack.remove(delete);
                    hDefense.remove(delete);
                    System.out.println("Hero has been deleted!");
                    StartPanel();
                } else {
                    StartPanel();
                }
     
            }
        }
     
    //This is a useful method which allows the user to view all current Hero characters in the ArrayList.
        public void ShowTeam() {
            System.out.println("\n");
            for (int i = 0; i < hName.size(); i++) {
                int counter = i + 1;
                System.out.println("H E R O   " + counter);
                System.out.println("-------------------------");
                System.out.println("Name: " + hName.get(i) + "\n" + " Age: " + hAge.get(i) + "\n" + " Race: " + hRace.get(i) + "\n" + " Attack: " + hAttack.get(i) + "\n" + " Defense: " + hDefense.get(i) + "\n" + "\n");
            }
        }
     
    //This stops the program from running.
        static void StopPro() {
            System.out.println("Ended");
            System.exit(0);
        }
    }
     
    //This is the main body which envokes the program
    class Hero {
     
        public static void main(String[] args) throws IOException {
            DataOutputStream outFile;
            DataInputStream inFile;
            String datafile = "binarydata.dat";
            try {
                inFile = new DataInputStream(new BufferedInputStream(new FileInputStream(datafile)));
     
     
                String tempName = "";
                String tempRace = "";
                int tempAge = 0;
                int tempAttack = 0;
                int tempDefense = 0;
     
                while (true) {
                    tempName = inFile.readUTF();
                    tempAge = inFile.readInt();
                    tempRace = inFile.readUTF();
                    tempAttack = inFile.readInt();
                    tempDefense = inFile.readInt();
                    System.out.format("The Hero %s is %d years old and is of the %s race, with an attack of %d and a defense of %d.%n", tempName, tempAge, tempRace, tempAttack, tempDefense);
                }
            } catch (FileNotFoundException fnf) {
                System.out.println("Error! The file " + datafile + "cannot be located.");
            } catch (EOFException e) {
                System.out.format("%nThis was the last information put through the file!%n");
     
     
     
            }
     
            HeroCreate heroChar = new HeroCreate();
     
     
            heroChar.StartPanel();
        }
    }

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    How do I read in the information from the file upon starting back up the program,
    You need to use methods that match the methods used to write the file to read it and in the same order,
    If you used writeInt() to write something, then you need to use readInt() to read it.

    it acts as though there are no objects in the array?
    Are there objects in the array? What does "acts as" mean? Is the array empty?
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Well there should be objects in the array, I made an array list for name, age, race, attakc and defense each. I then wrote them to the file, they read back perfectly fine but when I reopen the file in the program I want it to be able to read the same information without me re entering it. So basiaclly straight from the file.

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    So basiaclly straight from the file.
    Then you need a method that reads the file, gets the data and adds that data to the lists before starting with the menu for the user to respond to.
    If you don't understand my answer, don't ignore it, ask a question.

  19. The Following User Says Thank You to Norm For This Useful Post:

    MagicTricksKill (January 21st, 2013)

  20. #19
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Awesome, thanks! Do you have any idea where I could find a tutorial for that? Really strapped for time.

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    Sorry, I don't know of any tutorials for reading a file and saving the data in a list. Seems simple enough.
    You have code to read the data and code to add data to a list. Merge the logic for each into a method.
            tempName = inFile.readUTF();  // read name from file
       ...
            hName.add(newHeroName);  //  add a name to list
    If you don't understand my answer, don't ignore it, ask a question.

  22. The Following User Says Thank You to Norm For This Useful Post:

    MagicTricksKill (January 21st, 2013)

  23. #21
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: File Input and Output and Exception Handling

    Thanks so much for all your help, you're brilliant <3

  24. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File Input and Output and Exception Handling

    Good luck. You have the code here and there that does what you want. You just need to organize it a bit.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. File input and output
    By RKA in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: January 11th, 2013, 08:27 AM
  2. counting the values in input file and and writing the output to a file
    By srujirao in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 8th, 2012, 02:48 PM
  3. Input output file help
    By peteyfresh12 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 2nd, 2011, 07:44 AM
  4. Input/Output file help
    By Plural in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 25th, 2010, 08:34 PM
  5. Input/Output file help
    By Plural in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 23rd, 2010, 06:26 PM

Tags for this Thread