Where to put .txt file with SimpleInput

Hello everyone,
I'm rather new to Java and have a slight problem. The thing is that I need to write an app that can read a text file in this format:
2
Orc
name = Gnorck
experience = 20
maxHealthPoints = 50
healthPoints = 30
maxBerserk = 9
berserk = 7
Human
name = Aragorn
experience = 45
maxHealthPoints = 40
healthPoints = 30
maxGreed = 20
greed = 10
The first number is de number of characters in the file and after that every character is described in 7 lines.
Now the application has to be able to read the file. I've choosen to first just make a list of characters. A friend helped me with this code but I'm not completely sure if I know how it works. The code:
package RPGApplicatie;
import java.util.*;
public class Karakters {
     //Constructor
     public Karakters(int size){
          karakters = new ArrayList(size);
     //Methode voor het toevoegen van een karakter
     public void voegToe(Karakter k){
          karakters.add(k);
     public static Karakters readFile(String filename) throws ClassNotFoundException, RuntimeException, InstantiationException, IllegalAccessException{
          SimpleInput file = new SimpleInput(filename);
          int size = file.nextInt();
          Karakters result = new Karakters(size);
          for(int i = 0; i < size ; i++) {
               Class c = Class.forName(file.nextLine());
               result.voegToe((Karakter)c.newInstance());
          return result;
     //Variabelen aanmaken
     private ArrayList<Karakter> karakters;
}First question: I have the classes Karakter (which is the superclass for class Human and Orc), Human and Orc. So does the method forName scan for strings that are also classes? Like so it scans the file and when it comes across a line that says either 'Orc' or 'Human' it adds it to the list?
Second question: Where to put the text file that holds the data? I now have it in the same folder called test.txt. I use this code to run it:
package RPGApplicatie;
public class RPGApplicatie {
     public static void main(String[] args) throws ClassNotFoundException, RuntimeException, InstantiationException, IllegalAccessException {
          Karakters.readFile("test.txt");
}Thanks in advance! If more info is needed I can post that.
Regards,
Sander

I assume you have defined your Human and Orc classes to include fields name, experience, etc and a constructor that takes these values as parameters?
You can remove the Class.forName() method altogether. Example:
int count = file.readInt();
// define variables for Karakter values (name, experience etc.)
for (int i = 0; i < count; i++)
  String characterClass = file.readLine();
  // read common character components
  if (characterClass.equals("Human")
    // read human specific components
    karakters.add(new Human(...));
  if (characterClass.equals("Orc")
    // create Orc
//...Cheers

Similar Messages

  • Where to put .txt file for easy I/O

    Hi,
    I'm creating a program to run psychological experiments, and I want to make it easy for future researchers to change the lists of stimuli.
    I'm planning on having a set of .txt/.csv files containing the lists, which can be easily modified by anyone. My question is, where do I put them?
    My guess is the easiest solution would be to put them in the same folder as the .jar file, but not to actually include them in the .jar file, as this would make it difficult to edit. So how would I refer to the path name of the list in my program? And, when testing the program as it's being written, should I put the files in the /dist folder that NetBeans created?
    Second question: I want to find and load any and all txt files that may be in the folder (assuming this is where they will go). I won't know ahead of time how many lists there will be. What's the easiest way to do this?
    Thanks!

    Alright, two questions:
    1) To find the files, can I just use some modified form of
    String[] filenames;
              File f = new File(".");
              filenames = f.list();I assume that there's some way of doing the same thing one level up on the directory tree, and then selecting only those files that end in .csv? Is it preferable to use the method that was mentioned above?
    2) I'm still a little confused as to where the files should go. Here in NetBeans, when I use the command above it gives me everything in the very bottom folder, including /dist, /src and everything else in that folder, even though the .jar file itself is located in /dist.
    Is NetBeans not actually running the program from the .jar file?
    When I distribute the code, should I assume that the "File f = new File(".");" will give me everything in the folder where the .jar is sitting?
    [Edit: I've solved #2 myself -- sorry about that. The answer seems to be "yes" and "yes": when testing, I should put my .csv files in the bottom folder, when distributing, I should put them in the folder with the .jar file. I can't do it ahead of time, as NetBeans recreates the /dist folder each time the project is re-built.]
    Thanks!

  • How to get string (specified by line and column) from txt file with labview

    Hi everyone
    How to get string (specified by line and column) from txt file with labview
    thx 
    Solved!
    Go to Solution.

    As far as I know, a text file has no columns.  Please be more specific.  Do you mean something like the 5th word on line 4, where words are separated by a space, and lines are separated by a newline character?  You could the Read from Spreadsheet String function and set the delimiter to a space.  This will produce a 2D array of strings.  Then use index array and give the line number and column number.
    - tbob
    Inventor of the WORM Global

  • How can i put txt files in my i phone 4

    how can i put txt files in my i phone 4

    There are many apps for this.
    I use idisk with mobileme.
    You can search the apps store or do a forum search and find several others.

  • How to read the second line in a .txt file with bufferedReader?

    hi,
    i am not the best in speaking english and programming java :)
    so, just try to make sense of my question:
    Im using a BufferedReader to read a .txt file.
    the .txt file has 5+ different lines, and each line has 6 tokens (separated with ; )
    My java file has 6 textFields and each textfield is filled with one of the 6 different tokens.
    and my problem is:
    I want my buffered reader to read the next line (with 6 new different tokens) by pressing a button.
    if somethings not understandable, just ask :)

    maybe its easier to help me, when i publish my code, so here it is:
    (its my version, without Thof's code. Sorry, but the comments are the most in german)
    /* userdata.java */
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    public class userdata extends Frame {
    //-----------------------------------KlassenVariablen------------------------------------------------
    private JPanel panel = new JPanel ();
    String tokId = "";
    String tokName= "";
    String tokAge= "";
    String tokTel= "";
    String tokMail= "";
    String tokText= "";
    BufferedReader br;
    String zeile;
    StringTokenizer st;
    String delim = ";";
    //---------Buttons f?r Panel 1-------------------------
    Button first = new Button("|< First");
    Button back = new Button("< Back");
    Button next = new Button("Next >");
    Button last = new Button("Last >|");
    //---------Buttons f?r Panel 3-------------------------
    Button neu = new Button("New");
    Button safe = new Button("Safe");
    Button refresh = new Button("Refresh");
    //--------Labels f?r Panel 2-----------------------------
    Label lid = new Label("ID",Label.LEFT);
    Label lname = new Label("Name",Label.LEFT);
    Label lage = new Label("Age",Label.LEFT);
    Label ltel = new Label("Tel.",Label.LEFT);
    Label lmail = new Label("E-Mail",Label.LEFT);
    Label ltext = new Label("Spruch",Label.LEFT);
    Label lub = new Label("Last Button",Label.LEFT);
    TextField id = new TextField();
    TextField name = new TextField();
    TextField age = new TextField();
    TextField tel = new TextField();
    TextField mail = new TextField();
    TextField text = new TextField();
    TextField usedbutton = new TextField();
    //--------ActionEvent bla sachen eben--------------------
    public static void main (String[] args) throws IOException {
    userdata wnd = new userdata();
    wnd.setVisible(true);
    public userdata() throws IOException {                                                                                                                                                                                                                                                                                
    //--------------------------------Layout mit panel bestimmung--------------------------------------
    setLayout(new BorderLayout());
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();
    add(BorderLayout.NORTH ,p1);
    add(BorderLayout.CENTER , p2);
    add(BorderLayout.SOUTH , p3);
    //-------------------------------Funktionslose Buttons in PANEL 1------------------------------------
    p1.add(first);
    p1.add(back);
    p1.add(next);
    p1.add(last);
    p1.add(usedbutton);
    //--------------------------------Funktionierende Textfelder in PANEL 2------------------------------
    Panel labelpanel = new Panel();
    p2.setLayout(new GridLayout(7,3));
    p2.add(lid);
    p2.add(id);
    p2.add(lname);
    p2.add(name);
    p2.add(lage);
    p2.add(age);
    p2.add(ltel);
    p2.add(tel);
    p2.add(lmail);
    p2.add(mail);
    p2.add(ltext);
    p2.add(text);
    p2.add(lub);
    p2.add(usedbutton);
    //--------------------------------------Buttons in PANEL 3-----------------------------------------
    p3.add(neu);
    p3.add(safe);
    p3.add(refresh);
    //--------------------------------BufferedReader -------------------------------------------------
    readData();
    //--------------------------------Panel 2 TextField-----------------------------------------------
    fillForm();
    //================================ActionPerformed==================================================
    first.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    System.out.println ("First");
    usedbutton.setText("First");
    back.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    System.out.println ("Back");
    usedbutton.setText("Back");
    next.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    System.out.println ("Next");
    usedbutton.setText("Next");
    last.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    System.out.println ("Last");
    usedbutton.setText("Last");
    neu.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    System.out.println ("New entry");
    usedbutton.setText("New");
    safe.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    System.out.println ("Now Saving, do not turn off!");
    usedbutton.setText("Save");
    //-----------------refresh
    refresh.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    try{
    readData();
    }catch( IOException ioe){
    System.out.println("Fehler beim lesen aus Datei");
    fillForm();
    usedbutton.setText("Refresh");
    //=============================================================================Button Funktionen!!!
    pack();
    //--------------------------------WindowsListener hinzuf?gene--------------------------------------
    addWindowListener(
    new WindowAdapter() {
    public void windowClosing(WindowEvent event)
    setVisible(false);
    dispose();
    System.exit(0);
    //-----------------------------------readData() - > Buffered Reader in aktion! --------------------
    private void readData() throws IOException{
    BufferedReader br = new BufferedReader(new FileReader("My .txt File with path"));
    String zeile;
    StringTokenizer st;
    String delim = ";";
    zeile = br.readLine();
    st = new StringTokenizer(zeile, delim);
    st.hasMoreTokens();
    //System.out.println (st.nextToken());
    tokId = new String(st.nextToken());
    tokName = new String (st.nextToken());
    tokAge = new String (st.nextToken());
    tokTel = new String (st.nextToken());
    tokMail = new String (st.nextToken());
    tokText = new String (st.nextToken());
    //--------------------------fillForm() - > f?llt die TextFelder aus!--------------------------------
    private void fillForm(){
    id.setText(tokId);
    name.setText(tokName);
    age.setText(tokAge);
    tel.setText(tokTel);
    mail.setText(tokMail);
    text.setText(tokText);
    }

  • Export Excel Table in .txt File with space delimited text in UNICODE Format

    Hi all
    I've a big unsolved problem: I would like to convert an Excel table with some laboratory data in it (descriptions as text, numbers, variables with some GREEK LETTERS, ...). The output should be a formatted text with a clear structure. A very good solution is
    given by the converter in Excel "Save As" .prn File. All works fine, the formattation is perfect (it does not matter if some parts are cutted because are too long), but unfortunately the greek letters are converted into "?"!!!
    I've tried to convert my .xlsx File in .txt File with formatting Unicode and the greek letters are still there! But in this case the format is not good, the structure of a table is gone!
    Do you know how to save an Excel file in .prn but with Unicode formatting instead of ANSI or a .txt with space delimited text?
    Thanks a lot to everyone that can help me!
    M.L.C.

    This solution works in Excel/Access 2013.
    Link the Excel table into Access.
    In Access, right-click the linked table in the Navigation Pane, point your mouse cursor to "Export", and then choose "Text File" in the sub-menu.
    Name the file, and then under "Specify export options", check "Export data with formatting and layout".  Click "OK".
    Choose either Unicode or Unicode (UTF-8) encoding.  Click "OK".
    Click "Close" to complete the export operation.

  • Live view putting a file with no name

    So i have a problem (don't know if it's a problem really, but at least an annoyance) with the Live View and Preview in browser features.
    When use them, the file transfer window pops up (even if i have told it to stay "hidden") showing the following:
    Started: 29.5.2013 15.47
    index.php - same - not transferred
    Connections:Raspberrypi.php - same - not transferred
    styles:common.css - same - not transferred
    - error occurred - Access denied.  The file may not exist locally,  may be open in another program, or there could be a local permission problem.
    File activity incomplete. 1 file(s) or folder(s) were not completed.
    Files skipped: 3
    Files with errors: 1
    Finished: 29.5.2013 15.47
    So the weird lines are those marked with red. It looks like its trying to put a file with no name or extensions at all - and i don't think i have such files on my site. Also the permissions are correct on both the server and my Mac.
    My web browser opens up and shows the site perfectly, and if I'm using the Live View, the site shows up well too. The thing is every time I hit F5 to refresh, i have to close the file transfer window. Annoying.
    I don't know if it matters but I'm using a Raspberry Pi as my home web server. It has Apache2, PHP 5, MySQL and vsftpd running, and I have been able to use them with no problem earlier.
    Hopefully someone knows what I am doing wrong here...
    Thanks in adnvance!

    Have you enabled Automatic Upload on SAVE?  I never FTP files on Save.  Way too much risk of error and it takes focus away from my work which is very distracting.  See screenshot.
    Nancy O.

  • How do I get Firefox to ask me where to put a file I wish to download

    When I download a file, Firefox puts it somewhere. I want to be able to tell it where to put that file each and every time.

    Options > General - Downloads = '''Always ask me where to save files'''

  • How to get all paragraphs style and their fonts of a  indesign file and write all info with para info into txt file with scripting

    how to get all how to get all paragraphs style and their fonts of a  indesign file and write all info with para info into txt file with scriptingstyle and their fonts of a  indesign file and write all info with para info into txt file with scripting

    I write the script this one works
              var par=doc.stories.everyItem().paragraphs.everyItem().getElements();
      for(var i=par.length-1;i>=0;i--)
           var font=par[i].appliedParagraphStyle.name;
            var font1=par[i].appliedFont.name;
             var size=par[i].pointSize;
            WriteToFile (par[i].contents  +   "\r" +  "Style  : " + font  + "\r" +  "FONT1  : " + font1  + "\r" +  "Size  : " + size  + "\r", reportFilePath);
                            function WriteToFile(text, reportFilePath) { 
        file = new File(reportFilePath); 
        file.encoding = "UTF-8"; 
        if (file.exists) { 
            file.open("e"); 
            file.seek(0, 2); 
        else { 
            file.open("w"); 
          file.writeln(text);  
        file.close(); 
    Thanks for all your support

  • HOW TO READ TXT FILES with NOKIA 6300?

    I mean:
    I can see pics, video, listen mp3 but I cant read a txt file with Nokia 6300!!
    is there any application to do so? thanks!!!!!!!

    thanks well I tried 4 s far and none works.
    I tried: book_13, read_maniac, tiny-book, plus MobileHeart.com-test-book-831-2336.jar.
    it starts being frustrating.
    Can you suggest one you tested it works?
    -Also, I found that I cant' upload txt file while I can upload *.doc files.....do you know what's happening?
    thanks again.

  • How to put two files with the same name into the same folder?

    How can I put two files with the same name and the same extention into the same directory?
    Is this even possible?
    Thanks in advance. 

    Are you sure? I would be very surprised if that was the case.
    How does the computer/filing system differentiate the files, if not by their names?
    How do you tell the computer which one you want? (On the command line.)

  • I'm trying to put movies onto my hard  drive but i can't put the files with the same name onto the hard drive , finder won't let me change the name

    I'm trying to put movies onto my hard  drive but i can't put the files with the same name onto the hard drive , finder won't let me change the name. What am i doing wrong?

    Make a new folder and put them in that different folder. Then the names can be the same as others already on your drive.

  • [solved] Zim opens txt file with Wine Notepad

    I'm using KDE4.
    In Zim, Tools / Edit source opens the txt file with Wine Notepad. I guess this is the default association for txt files in GTK. How can I change this without using Gnome?
    Last edited by SanskritFritz (2010-10-18 07:04:58)

    Yes ,desktop and mimelist files in ~/.local. I have survived these anomalies to learn its much less pain to use windoze apps under virtualization environment than under emulation. And poweroff the virtual machine whenever it hangs.

  • How to open and edit "*.txt" file with "Notepad"

    Hello guys!
    I'm facing problem with SharePoint 2010 Enterprise and got no clue how to solve it.
    What I want to do is to open "*.txt" (which is placed to "Documents Library") in "Notepad", so I could edit it and save (publish) directly to SharePoint from "Notepad".
    If I upload any Microsoft office File, such as "*.docx", "*.xls", etc - it works as it should - document opens in appropriate application and everybody is happy.
    But, when I create documents library, put some "*.txt" file there and click on it - it opens in new browser's tab as text, so I cannot edit the file.
    What I tried to do is to activate feature "Open Documents in Client Applications by Default" - not happy.
    Edit "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\DOCICON.XML" - I've modified "txt" entry as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <DocIcons>
        <ByProgID>
        </ByProgID>
        <ByExtension>
    <Mapping Key="txt" Value="ictxt.gif" EditText="Notepad" OpenControl="SharePoint.OpenDocuments"/>
        </ByExtension>
        <Default>
            <Mapping Value="icgen.gif"/>
        </Default>
    </DocIcons>
    Still not happy.
    So, how do I make this stuff work?

    Found this link which has more information on this scenario:
    http://sharepoint.stackexchange.com/questions/1427/open-txt-file-in-notepad-from-sharepoint
    A programmatic workaround:
    http://weblogs.asp.net/bsimser/archive/2005/01/24/359911.aspx
    Andrew Milsark, MCITP,MCTS
    Fpweb.net - The SharePoint Hosting Pioneer
    Blog : http://blog.fpweb.net
    Twitter : http://www.twitter.com/amilsark

  • Where to put jar files reachable for ejb:s?

    Hello!
    I have a ejb that use some jar files.
    But I can not figure out where to put the jar files that I use from my ejb in Weblogic 8.1.3.
    Until now I have extracted all jar files and put them inside my ejb with my own class files. But this seems odd.
    So please help me out here.
    Best regrads
    Fredrik

    Dear,
    You might have downloaded either tar.gz or zip file. when you extract this file you will find a jar file and also some demos nad docs(api+help). place the poifs api jar file in 'WEB-INF\lib" folder and restart the server.
    In general any api jar files for web applications should be placed in WEB-INF\lib folder then only they are accesible. If you extracted the jar, then place entire package structure in WEB-INF\classes directory
    Regards,
    Nishant Kulkarni
    Software Engineer
    Bangalore
    [email protected]

Maybe you are looking for