Java File Access                 

   Contact
   C
   C++
   Visual Basic
   Java
   JavaScript
   DHTML
   Style Sheets
   About
   Normalization
   Active X
   TDC Binding
   PHP
   Perl and CGI
   Flash
   XML
   SQL
   Chat
   MCSE
   Linux
   Cabling   
 

   
 
    
    
Java 2  Java 3  Supplementary  Events  AWT Project  AWT Project  Language  Swing  Sound/Images

File Access comes in three varieties under Java. There are plain ASCII sequential text files, there are random access files, and there are binary files. All methods of accessing data will involve an instantiation of class objects in Java. Sequential files require instantiation of
the File class. It contains these methods:

canRead()
canWrite()
exists()
getName()
getPath()
getParent()
length()
lastModified()

The examples below come from the seven different classes that make up the adventure game project here: ADVENTURE GAME.
Some utilize instances of the character class defined in that project. They cover serialization (the act of writing an entire class
object to a file and converting its different data types for storage and retrieval).

import javax.swing.*;
import java.io.*;
public class ZeeDatabase
{
       public static final int NumEmps = 3; //Global
    
       //Unlike C++, nested classes are allowed in Java. When you compile a nested class, Java
         //will compile each nested class in separate files as "ParentClass$NestedChildClass".
       public static class Employee
       {
              public Employee() {  }           
              public void DisplayInfo()
              {
                     System.out.print("\tEmployee ID #:" + ID +
                     "\n\t\tFirst Name: " + FirstName +
                     "\n\t\tLast Name: " + LastName +
                     "\n\t\tSocial Security Number: " + Social +
                     "\n\t\tPay Rate: " + PayRate + "\n\n"); 
              }
              public void setID(int x) { ID = x; }              
              public void setFirst(String x) { FirstName = x; }
              public void setLast(String x) { LastName = x; }
              public void setSocial(int x) { Social = x; }
              public void setPayRate(double x) { PayRate = x; }
              public int getID() { return ID; }              
              public String getFirst() { return FirstName; } 
              public String getLast() { return LastName; } 
              public int getSocial() { return Social; } 
              public double getPayRate() { return PayRate; }       
              private int ID = 1;
              private String FirstName = "";
              private String LastName = "";
              private int Social = 0;
              private double PayRate = 0.0;
       }//close nested Employee class
      
      public static void main(String[] args) throws IOException 
      { 
            char choice = '#';
            boolean EndIt = false; 
            while(EndIt == false)
            {          
                System.out.println("\n\n\tEmployee Database Menu");
                System.out.print("\n\n\t(A)dd Employees" +
                                 "\n\t(L)ist Employees" +
                                 "\n\t(Q)uit\n\n\t");
                 choice = CINchar();                  
                 switch(choice)
                 {
                     case 'a' : AddEmployees(); break;
                     case 'l' : ListEmployees(); break;
                     case 'q' : EndIt = true; break;
                     default : System.out.println("\tThat was an invalid choice."); break;
                 }//close switch statement
            }//close while loop
            System.exit(0); 
      }//close main() function 
      
       public static void AddEmployees() throws IOException 
       {
              try 
              {
                  DataOutputStream outtie;
                  outtie = new DataOutputStream(new FileOutputStream("EmployeeData.txt"));
                  Employee EMP = new Employee(); 

                  for(int x = 0; x < NumEmps; x++)
                  {
                      System.out.println("\nEntry " + (x+1) + " of " + NumEmps + "\n");

                      System.out.print("\nEnter employee's ID: ");
                      EMP.setID(CINInteger()); 

                      System.out.print("\nEnter employee's first name: ");
                      EMP.setFirst(CINString());

                      System.out.print("\nEnter employee's last name: ");
                      EMP.setLast(CINString()); 

                      System.out.print("\nEnter employee's social security number: ");
                      EMP.setSocial(CINInteger());

                      System.out.print("\nEnter employee's pay rate: ");
                      EMP.setPayRate(CINDouble());
 
                      outtie.writeInt(EMP.getID());
                      outtie.writeUTF(EMP.getFirst());
                      outtie.writeUTF(EMP.getLast());
                      outtie.writeInt(EMP.getSocial());
                      outtie.writeDouble(EMP.getPayRate()); 

                  }//close for loop

                  outtie.close();

              }//close try 

              catch (IOException e) { System.err.print("Unable to open file."); }
       }//close AddEmployees() function
       
       public static void ListEmployees() throws IOException 
       {
              try 
              {
                  DataInputStream innie;
                  innie = new DataInputStream(new FileInputStream("EmployeeData.txt"));
                  Employee EMP = new Employee(); 

                  //In Java, there is no ".eof()" function. Instead, read() returns -1 at EOF. 
                  for(int x = 0; x < NumEmps; x++)
                  { 
                      System.out.print("\nEntry " + (x+1) + " of " + NumEmps + ":");

                      EMP.setID(innie.readInt());
                      EMP.setFirst(innie.readUTF());
                      EMP.setLast(innie.readUTF());
                      EMP.setSocial(innie.readInt());
                      EMP.setPayRate(innie.readDouble()); 
                      EMP.DisplayInfo();
                  }//close for

                  innie.close();

              }//close try

              catch (IOException e) { System.err.print("\tUnable to open file."); }
       }//close AddEmployees() function
       

//-----------------------------------------------------------------------------------------   

       public static char CINchar()
       {
              LineNumberReader cin = new LineNumberReader(new InputStreamReader(System.in));
              String choice = "";
              char WhatToLookFor = '#';
              try { choice = cin.readLine(); }              
              catch (IOException e) { System.err.println("\tError."); }
              choice.toLowerCase();
              //In case it's empty
              if(choice.equals("")) { WhatToLookFor = '#'; }
              else { WhatToLookFor = choice.charAt(0); }  
              return WhatToLookFor;
       } 

      
       public static double CINDouble()
       {
              LineNumberReader cin = new LineNumberReader(new InputStreamReader(System.in));
              String choice = "";
              double WhatToLookFor = 0.0;
              try { choice = cin.readLine(); }              
              catch (IOException e) { System.err.println("\tError."); }
              choice.toLowerCase();
              if(choice.equals("")) { WhatToLookFor = 0.0; }
              else
              {
                   
//We need to handle the error if they don't enter a number
                    try { WhatToLookFor = Double.parseDouble(choice); }
                    catch(NumberFormatException e)
                    {
                       System.out.println("\tThat was not a number!");
                       WhatToLookFor = 0.0;
                   }
              }
              return WhatToLookFor;
       }
//----------------------------------------------------------------------------------------- 

       public static int CINInteger()
       {
              LineNumberReader cin = new LineNumberReader(new InputStreamReader(System.in));
              String choice = "";
              int WhatToLookFor = 0;
              try { choice = cin.readLine(); }              
              catch (IOException e) { System.err.println("\tError."); }
              choice.toLowerCase();
              if(choice.equals("")) { WhatToLookFor = 0; }
              else
              {
                   
//We need to handle the error if they don't enter a number
                    try { WhatToLookFor = Integer.parseInt(choice); }
                    catch(NumberFormatException e)
                    {
                       System.out.println("\tThat was not a number!");
                       WhatToLookFor = 0;
                   }
              }
              return WhatToLookFor;
       }

       public static String CINString()
       {
              LineNumberReader cin = new LineNumberReader(new InputStreamReader(System.in));
              String choice = "";
              try { choice = cin.readLine(); }              
              catch (IOException e) { System.err.println("\tError."); }
              return choice;
       }

}//close ZeeDatabase class

Example 1 - Simple ASCII File Access (writing):

import javax.swing.*;
import java.io.*
;

public
class CreatingAClass
{
      public void main(String[] args)
      {
             SaveHighScores();
             System.exit(0);
      }
//close main() function
 
       boolean SaveHighScores(Character CurrentPlayer)
       {
            boolean successful = false;
           
            try
            {
                File scores = new File("highscores.txt");
                FileOutputStream highscores;
               
                if (scores.exists())
                {
                    System.out.println(
                    "\thighscores.txt already exists -- appending new score to it.");
                   
//"true" = append, 2 arguments
                    highscores = new FileOutputStream(scores, true);
                }   
      
                else
                {
                    System.out.println(
                    "\thighscores.txt does not exist -- I'll create it!");
                    highscores = new FileOutputStream(scores);
//no append, 1 argument
                }               
               
                PrintStream hiscores = new PrintStream(highscores);
                hiscores.println(CurrentPlayer.getName());
                hiscores.println(CurrentPlayer.getScore()); 
                hiscores.close(); highscores.close();
                successful = true
            }

            catch (IOException e)
            {
                System.out.print("ERROR saving scores.");
                successful = false;
            }
    
            return successful;
       }
 //close SaveHighScores() function

}
//close CreatingAClass class

Example 2 - Simple ASCII File Access (reading):

import javax.swing.*;
import java.io.*
;

public
class CreatingAClass
{
      public void main(String[] args)
      {
             DisplayHighScores();
             System.exit(0);
      }
//close main() function
 
      boolean DisplayHighScores()
      {
              System.out.print("\n\n\n");
              boolean successful = false;
         
              String HoldMeStringName = "";
              String HoldMeStringInteger = "";
              int HoldMeInteger = 0;
              int z = 0;
              int x = 0;

              try
              {       
                 File scores = new File("highscores.txt");
                 FileInputStream highscores = new FileInputStream(scores);
                 InputStreamReader hiscores = new InputStreamReader(highscores);
                 BufferedReader SCORES = new BufferedReader(hiscores);

                   while(HoldMeStringName != null)
                   {
                       HoldMeStringName = SCORES.readLine();
                       HoldMeStringInteger = SCORES.readLine();
                       x++; 
//add one for every 2 lines (name and score pair)
                   }
                    
                   x = x - 1;
//Subtract 1 for the offset (one too many)
                    
                   String[] NAMES = new String[x];
                   int[] TheSCORES = new int[x];
                    
                  
//Reset all the stream and file objects, move pointer back to beginning
                   scores = new File("highscores.txt");
                   highscores = new FileInputStream(scores);
                   hiscores = new InputStreamReader(highscores);
                   SCORES = new BufferedReader(hiscores);
                    
                  
//Put each line into
                   for(z = 0; z < x; z++)
                   {
                       NAMES[z] = SCORES.readLine();
                       HoldMeStringInteger = SCORES.readLine();
                       TheSCORES[z] = Integer.parseInt(HoldMeStringInteger);
                    
                   }
                    
                     highscores.close();
                    
                     System.out.println("\t\tTotal of " + x +
                     " score records present in file.\n");
       
                     for(int q = 0; q < x; q++)
                     {
                         for(int r = 1; r < x; r++)
                         {
                             if(TheSCORES[r] > TheSCORES[r - 1])
                             {
                                HoldMeInteger = TheSCORES[r];
                                HoldMeStringName = NAMES[r];
                                TheSCORES[r] = TheSCORES[r - 1];
                                NAMES[r] = NAMES[r - 1];
                                TheSCORES[r - 1] = HoldMeInteger;
                                NAMES[r - 1] = HoldMeStringName;          
                             }
                         }
                     }
       
                     System.out.print(
                     "\t\t***************** High Scores *****************\n\n");
                     System.out.print(
                     "\t\t-----------------------------------------------\n");

             for(z = 0; z < x; z++)
                     {
                        System.out.print("\t\t" + (z+1) + ". Name: " + NAMES[z] +
                                         "  Score: " + TheSCORES[z] + "\n");
                        System.out.print(
                     "\t\t-----------------------------------------------\n");   
                     }

             System.out.print(
                     "\n\t\t***********************************************\n");
                     System.out.print("\n\n\t\t\t");
                     PAUSE();
                     successful = true;
               }
              
               catch(IOException e)
               {
                   System.out.print(
                   "\tUnable to find \"highscores.txt\" or read scores.\n");
                   successful = false;
               }
        
               //Declared 2 Parallel Arrays where # elements = # lines.
               //Above is a Bubble Sort for High Scores. Go through each Name
               //and Score set and swap to arrange in descending order

               return successful;
       
       }
//close DisplayHighScores() Function


}
//close CreatingAClass class

Example 3 - Serialization (writing):

import javax.swing.*;
import java.io.*
;

public
class CreatingAClass
{
      public void main(String[] args)
      {
             SaveCharacter();
             System.exit(0);
      }
//close main() function
 
      boolean SaveCharacter(Character CurrentPlayer)
       {                    
              boolean successful;
              String CharacterName = "";
              String passwd = "";
    
              System.out.print("\n\tEnter the file name to save as: ");
              
              try { CharacterName = cin.readLine(); }              
              catch (IOException e) { System.err.println("Error."); }
              
              CharacterName = CharacterName + ".gam";
  
              System.out.print("\n\tEnter a password:   ");
              
              try { passwd = cin.readLine(); }              
              catch (IOException e) { System.err.println("Error."); }
    
              try
              {
                   File PlayerFile = new File(CharacterName);
                   FileOutputStream PlayerObject;
                   PlayerObject = new FileOutputStream(PlayerFile);  
                   PrintStream WritePlayer = new PrintStream(PlayerObject);
                  
                   //Simple serialization of Character class in plain ASCII
                   WritePlayer.println(passwd);                       
                   WritePlayer.println(CurrentPlayer.getName());
                   WritePlayer.println(CurrentPlayer.getHit());
                   WritePlayer.println(CurrentPlayer.getAttack());
                   WritePlayer.println(CurrentPlayer.getDefense());                       
                   WritePlayer.println(CurrentPlayer.getLevel());
                   WritePlayer.println(CurrentPlayer.getScore());
                   WritePlayer.println(CurrentPlayer.getLocation());        

                   WritePlayer.println(CurrentPlayer.getDagger());
                   WritePlayer.println(CurrentPlayer.getSword());
                   WritePlayer.println(CurrentPlayer.getLongBow());
                   WritePlayer.println(CurrentPlayer.getChainMail());              
                   WritePlayer.println(CurrentPlayer.getFullBodyArmor());
                   WritePlayer.println(CurrentPlayer.getHealingPotion());
                   WritePlayer.println(CurrentPlayer.getFishKey());
         
                   WritePlayer.println(W1GiantAlive);
                   WritePlayer.println(E1DragonAlive);
                   WritePlayer.println(S2MotleyCrewAlive);              
                   WritePlayer.println(FirstTimeInShamanHut);
                   WritePlayer.println(CENTERFirstTime);
                   WritePlayer.println(UNDERDragonPairAlive);
                   WritePlayer.println(FoundHP_West2);
                   WritePlayer.println(FoundHP_Shaman);
                  
                   WritePlayer.close(); PlayerObject.close();
                   successful = true
            }
           
            catch (IOException e)
            {
                System.out.print("ERROR saving character file.");
                successful = false;
            }
                 
            return successful;
       }



}
//close CreatingAClass class

Example 4 - Serialization (reading):

import javax.swing.*;
import java.io.*
;

public
class CreatingAClass
{
      public void main(String[] args)
      {
             LoadCharacter();
             System.exit(0);
      }
//close main() function
 

      //No method to convert String to boolean in Java as in C++, so let's make our own!    
      public boolean TrueOrFalse(String x)
      {
              if(x.equals("true"))  { return true; }
              else { return false; }
      }



      boolean LoadCharacter(Character CurrentPlayer)
      {
              boolean successful;
           
              String CharacterName = "";
              String nm = "";
              String passwd = "";
              String pass = "";
           
              String hp = "";
              String atk = "";
              String def = "";
              String lvl = "";
              String scr = "";
              String loc = "";
           
              String dagger = "";
              String sword = "";
              String bow = "";
              String mail = "";
              String armor = "";
              String healing = "";
              String fkey = "";
           
              String giant = "";
              String dragon = "";
              String motley = "";
              String shaman = "";
              String center = "";
              String under = "";
              String HPwest2 = "";
              String HPshaman = "";
          
              System.out.print("\n\tEnter the name of the Character to load: ");
 
              try { CharacterName = cin.readLine(); }              
              catch (IOException e) { System.err.println("Error."); }
              
              CharacterName = CharacterName + ".gam";
  
              System.out.print("\n\tEnter the password:   ");

              try { passwd = cin.readLine(); }              
              catch (IOException e) { System.err.println("Error."); }
         
              try
              {       
                File PlayerFile = new File(CharacterName);
                FileInputStream PlayerObject = new FileInputStream(PlayerFile);
                InputStreamReader ReadPlayer = new InputStreamReader(PlayerObject);
                BufferedReader StreamPlayer = new BufferedReader(ReadPlayer);

                pass = StreamPlayer.readLine();
             
                if(pass.equals(passwd))
                {
 
                        //Careful! serialization = you must read in exactly the same order as you wrote!
                   nm = StreamPlayer.readLine();
                   hp = StreamPlayer.readLine();
                   atk = StreamPlayer.readLine();
                   def = StreamPlayer.readLine();             
                   lvl = StreamPlayer.readLine();
                   scr = StreamPlayer.readLine();
                   loc = StreamPlayer.readLine();

                   dagger = StreamPlayer.readLine();
                   sword = StreamPlayer.readLine();
                   bow = StreamPlayer.readLine();             
                   mail = StreamPlayer.readLine();
                   armor = StreamPlayer.readLine();
                   healing = StreamPlayer.readLine();
                   fkey = StreamPlayer.readLine();

                   giant = StreamPlayer.readLine();   
                   dragon = StreamPlayer.readLine();   
                   motley = StreamPlayer.readLine();                 
                   shaman = StreamPlayer.readLine();  
                   center = StreamPlayer.readLine();  
                   under = StreamPlayer.readLine();   
                   HPwest2 = StreamPlayer.readLine(); 
                   HPshaman = StreamPlayer.readLine();             
               
                  
//Read it in as a string, have to convert it to an integer
                   CurrentPlayer.setName(nm); 
                   CurrentPlayer.setHit(Integer.parseInt(hp));
                   CurrentPlayer.setAttack(Integer.parseInt(atk));
                   CurrentPlayer.setDefense(Integer.parseInt(def));       
                   CurrentPlayer.setLevel(Integer.parseInt(lvl));
                   CurrentPlayer.setScore(Integer.parseInt(scr));
                   CurrentPlayer.setLocation(Integer.parseInt(loc));                   
                  
                         //Read it in as a string, have to convert it to an boolean
                   CurrentPlayer.setDagger(TrueOrFalse(dagger));
                   CurrentPlayer.setSword(TrueOrFalse(sword));
                   CurrentPlayer.setLongBow(TrueOrFalse(bow));
                   CurrentPlayer.setChainMail(TrueOrFalse(mail));
                   CurrentPlayer.setFullBodyArmor(TrueOrFalse(armor));
                   CurrentPlayer.setHealingPotion(Integer.parseInt(healing));
                   CurrentPlayer.setFishKey(TrueOrFalse(fkey));
                 
                   W1GiantAlive = TrueOrFalse(giant);
                   E1DragonAlive = TrueOrFalse(dragon);
                   S2MotleyCrewAlive = TrueOrFalse(motley);
                   FirstTimeInShamanHut = TrueOrFalse(shaman);
                   CENTERFirstTime = TrueOrFalse(center);
                   UNDERDragonPairAlive = TrueOrFalse(under);
                   FoundHP_West2 = TrueOrFalse(HPwest2);
                   FoundHP_Shaman = TrueOrFalse(HPshaman);

                   ReadPlayer.close(); PlayerObject.close();
                   successful = true;
               }
              
               else
               {
                    System.out.print("\n\tThat was not the correct password!!!");
                    successful = false;
               }           
            }
           
            catch(IOException e)
            {
                System.out.print("\tUnable to create charactrer file.\n");
                successful = false;
            }

            return successful;
          
       }
//close LoadCharacter() function

}
//close CreatingAClass class



Sequential Access Files - Sequential Access files utilize different methods to write different data types:

writeChar()
writeInt()
writeDouble()
writeFloat()
writeLong()
writeUTF()
readChar()
readInt()
readDouble()
readFloat()
readLong()
readUTF()

 

Java 2  Java 3  Supplementary  Events  AWT Project  HOME  AWT Project  Language  Swing  Sound/Images