Reading and Writing to a file


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Reading and Writing to a file

Hybrid View

  1. #1
    Join Date
    Nov 2005
    Posts
    2

    Reading and Writing to a file

    I am having a problem reading and writing to a file. I have 2 classes (HighScores & PlayersNameFrame). I need to take the users name in (currently stored to tempName) and then write that to a file. I need to write the Users name and Score to a file called "HighScores.txt" and read from the file to the pop up window everytime the users clicks the high scores button form the main program. Any ideas how to do it? This is what I have so far.

    class HighScoresFrame extends JDialog implements ActionListener
    {
    private JButton ExitBtn;
    private Container dPane;

    String people[] = new String[10]; //Names of the people
    int scores[] = new int[10]; //People's scores

    String name;
    int score;


    public HighScoresFrame(final JButton HighScoresBtn, JFrame owner)
    {
    super(owner, "High Scores", true);

    //set content pane, which we need to add stuff to frame
    dPane = this.getContentPane();

    /*Using awt toolkit to help center window on screen*/
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    int width = 325;
    int height = 400;
    setBounds((d.width-width)/2, (d.height-height)/2, width, height);
    setResizable(false);


    //create a panel to hold the grid
    JPanel a = new JPanel();

    ExitBtn = new JButton ("Exit");
    ExitBtn.addActionListener(this);
    a.setLayout(new FlowLayout(FlowLayout.CENTER));
    a.add(ExitBtn);
    dPane.setLayout(new BorderLayout());
    dPane.add(a, BorderLayout.CENTER);
    String n ="";
    int s = 0;

    name = n;
    score = s;
    update();


    }//ends HighScoresFrame

    public void update()
    {
    try
    {
    //Reads the file
    BufferedReader input = new BufferedReader( new FileReader("highscores.txt") );
    String line = null;
    int i = 0;
    while (( line = input.readLine()) != null)
    {

    scores[i] = Integer.valueOf(line.substring(line.indexOf(";") + 1)).intValue(); //gets score
    people[i] = line.substring(0, line.indexOf(";")); //gets person
    i++;

    }
    input.close();



    for(int k = 0; k < 10; k++)
    {
    if(score >= scores[k])
    {
    //change order
    }
    else
    {

    }
    }


    //Writes the file
    BufferedWriter output = new BufferedWriter(new FileWriter("highscores.txt"));
    for(int j = 0; j < 10; j++)
    {
    output.write(Integer.toString(scores[j]) + ";" + people[j]);
    output.newLine();
    }
    output.close();

    } catch(Exception e) {

    }
    }


    public void actionPerformed(ActionEvent e)
    {
    Object source = e.getSource();

    if( source == ExitBtn )
    {
    //System.exit(0);
    dispose();

    }
    }//ends actionPerformed Highscores frame

    }//ends High Scores Main Frame





    //Pops up JDialog window to get users name
    class PlayersNameFrame extends JDialog implements ActionListener
    {
    private Container ePane;
    private JTextArea UsersName;
    private JLabel NameOfUser;
    private JButton usersnamebtnExit;
    private JButton saveBtn;
    private String tempName;

    public PlayersNameFrame(JFrame owner)
    {
    super(owner, "Players Name", true);

    //set content pane, which we need to add stuff to frame
    ePane = this.getContentPane();

    //Sets Screen Size and does not allow user to resize
    setSize(325,120);
    setResizable(false);

    //create panels
    JPanel a = new JPanel(); //Panel will be located in the North of box
    JPanel b = new JPanel(); //Panel will be located in the Center of box
    JPanel c = new JPanel(); //Panel will be located in South of box

    //Create a Text Area
    UsersName = new JTextArea(1,20); //Sets size to 1 X 20
    UsersName.setFont(new Font("Serif", Font.BOLD, 13)); //Sets font to Serif, Bold, 12
    UsersName.setLineWrap(false); //Allows for line wrap
    UsersName.setEditable(true); //Doesn't allow user to edit field
    UsersName.setWrapStyleWord(false);

    //Create a JLabel area
    NameOfUser = new JLabel ("Please enter your Initials");

    //create some buttons
    saveBtn = new JButton ("Save");
    usersnamebtnExit = new JButton("Exit");

    //add action listenters to buttons
    usersnamebtnExit.addActionListener(this);
    saveBtn.addActionListener(this);

    a.setLayout(new FlowLayout(FlowLayout.CENTER));
    b.setLayout(new FlowLayout(FlowLayout.CENTER));

    //add things to frame
    a.add(NameOfUser); //Adds JLabel to top of screen
    b.add(UsersName); //Adds Text area to center of screen
    c.add(saveBtn); //Adds Buttons to south part of screen
    c.add(usersnamebtnExit); //Adds Buttons to south part of screen

    //add components to frame
    ePane.setLayout(new BorderLayout());
    ePane.add(a, BorderLayout.NORTH);
    ePane.add(b, BorderLayout.CENTER);
    ePane.add(c, BorderLayout.SOUTH);

    //set some frame properties that we want...
    //setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);



    }//PlayersName Constructor

    /**action event handler*/
    public void actionPerformed(ActionEvent e)
    {
    Object source = e.getSource();

    if( source == usersnamebtnExit )
    {
    //System.exit(0);
    dispose();
    }
    else
    {
    tempName = UsersName.getText();
    System.out.println(tempName);
    dispose();
    }
    }//ends actionPerformed

    }//Ends PlayersName Main

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    File IO in java looks something like this:
    Code:
    // Input from file
    BufferedReader in = new BufferedReader(new FileReader("filename"));
    String line;
    while( (line = in.readLine()) != null ) {
      // ... process the line of text (in your case make a label with the text or something like that
    }
    
    // Output to file
    PrintWriter out = new PrintWriter(new File("filename"));
    out.println("text to output");
    The one thing that you have to keep in mind is that any time that you open a file, you are going to have to put the code in a try{}catch block which will catch the IOException which most of the constructors can throw.

    Hope this helps.
    ~evlich

Similar Threads

  1. Reading and writing lines from a text file...
    By Jenks in forum VB Classic
    Replies: 6
    Last Post: 05-24-2005, 02:22 PM
  2. Replies: 0
    Last Post: 04-22-2002, 06:06 PM
  3. Replies: 1
    Last Post: 04-22-2002, 05:59 PM
  4. NullPointerException when reading text file
    By Andrew McLellan in forum Java
    Replies: 3
    Last Post: 05-09-2001, 05:34 PM
  5. reading and writing a file
    By rzions in forum Web
    Replies: 0
    Last Post: 02-08-2001, 12:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center