email me at borlaj@portlandschools.org

Loading
notes previous (12/<12) submit the dump links  
 

Reading and writing files

 

This is hard in an applet (you need security settings in order to access local files) so we will do it in an application (look here on how to convert).

 

Here is a sample application. (unzip somewhere)

 

 

 

Put this class in your project. Here is the API.

 

 

 

To use it, say something like:

MyFile m=new MyFile("t.txt");
String contents=m.allLines();
m.replaceFile("New contents");               

 

Below is the class for your viewing pleasure

  
/**
 * This class is used to read and write a file 
 * 
 * @author Jeff Borland
 * @version 12-10-11
 */
import java.io.*;
import java.util.ArrayList;
public class MyFile
{
    File theFile;
    ArrayList fileContents = new ArrayList();  //I use a list to store each line of the file
    int currentLocation=0;
    
    /**
     * When constructed, MyFile requires a string of the file location.  
     * If in the same folder, just put its name, otherwise put its entire path like c:\test.txt
     */
    public MyFile(String str)
    {
        theFile = new File(str);
        try{
            FileInputStream fstream = new FileInputStream(theFile);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // Print the content on the console
                fileContents.add(strLine);
            }
        }
        catch (Exception e)
        {
        }
    }

    /**
     * Returns the nextLine read from the file
     */
    public String nextLine()
    {

        if (currentLocation<=fileContents.size())
        {            
            String current= fileContents.get(currentLocation);
            currentLocation++;
            return current;
        }
        else
            return null;
    }

    /**
     * Return the entire file as a string
     */
    public String allLines()
    {
        String all="";
        for (String s:fileContents)
            all+=s+"\n";
        return all;
    }

    /**
     * This will replace (or create) a file with the contents String str
     */
    public boolean replaceFile(String str)
    {
        try{            
            FileWriter fstream = new FileWriter(theFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(str);
            //Close the output stream
            out.close();
            return true;
        }catch (Exception e){//Catch exception if any
            return false;
        }
    }

    /**
     * Add String str to the end of the file
     */
    public boolean addToFile(String str)
    {
        fileContents.add(str);
        String all="";
        for (String s:fileContents)
            all+=s+"\n";
        try{            
            FileWriter fstream = new FileWriter(theFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(all);
            //Close the output stream
            out.close();
            return true;
        }catch (Exception e){//Catch exception if any
            return false;
        }
    }
    
    /**
     * Deletes a line from the file
     */
    public boolean deleteLine(int line)
    {
        fileContents.remove(line);
        currentLocation=0;
        return addToFile("");
    }
}
    
            

Class Assignment:

  1. Create an app called Welcome that will either pop up w/ a dialog box that says Whats your name? And read that in, storing it as a textbox, or it will say Welcome Jeff Borland if it knows who you are.
  2. Create an app called PhoneList that will have the user put in names (textfield) and phone number (textfield), with a button for add to phone list. It will also have a phone list with all names-phone nums in the system.
  3. Create an app called RunningTracker that will track how many miles that users has run. It will have a textfield where they will enter the number of miles they ran that day. It will say they have run a total of ___ miles. Remember Integer.parseInt(str) will convert str (a string) to an int.

Advanced

  1. Create an app called TriathlonTracker where the user will have an combobox option of Run, Swim, Bike and the number of minutes down with each exercise. When they hit submit, it will add to the file. It will say somewhere the total number of minutes done with each exercise and their average. Like swimming 6.7 hours, averaging 25 minutes a workout.