Martrinex Learning Center
HOME CONTENTS
 
This website is underconstruction.
Author: Martin Sykes
Challenge: I have challenged myself to 1 article per day, and framework improvements! Enjoy
Challenge end: unknown

File Input / Output

Thus far everything we have done, all the user input we have recieve, we have lost when the program has been closed, as you can imagine this isn't exactly productive, to to save to text files.

Output

Using the code from myLogon:
Download

myLogon2.zip [5.9kb]
This code currently has a DATABASE class which holds an Array of 50 USERS, we are now going to update this so it can save them users and load them from a textfile on the harddrive. :-)
Tasks:

Class USER

Code:
public USER(String userdata){

fromString(userdata);
}

public String toString(){

return strUsername+":"+strPassword;
}

public void fromString(String userdata){

int seperator = userdata.indexOf(":");
strUsername = userdata.substring(0, seperator);
strPassword = userdata.substring(seperator+1);
}
toString is a standard function for classes in Java, it tries to convert the values of a class in to a readeable String format, you can override this function as we have just done! fromString is obviously the reverse but it is not a standard function of Java.

Class DATABASE

Code:
public void save() throws IOException{

PrintStream out = new PrintStream(new FileOutputStream("users.ini"));
for (int i = 0; i < count; i++){

out.println(users[i].toString());
}
out.close();
}

public void load() throws IOException{

int c;
FileInputStream in;
// open file if it exists
try{

in = new FileInputStream("users.ini");
} catch(FileNotFoundException e){

return; // if not do nothing
}
// create a String to hold file data
StringBuffer buf = new StringBuffer();

// read file 1 char at a time
/* char 10 is carriage (we ignore/remove these)
* char 13 is return (we add a new user when we see these)
*/

do {

c = in.read();
if(c==13){
// 13 meens return, meens new line, 1 line per USER
if(buf.length()!=0) users[count++]= new USER(buf.toString());
//count++;
buf = new StringBuffer(); // empty the string
} else{

if(c!=10) buf.append((char) c); // add charactor to the end of the string
}
} while (c != -1); // -1 is the end of the file
in.close();

}

public void dump(){

System.out.println("Username : Password");
System.out.println("-------------------");
for (int i = 0; i < count; i++){

System.out.println(users[i].toString());
}
System.out.println("-------------------");
System.out.println("Count: "+count);
}

public void clear(){

count = 0;
}
throws IOException Again we are not really handling bugs, just passing them on from one function, to the main function and out of the program, the reason IOException is needed is incase: the file does not exist, the folder needs admin permissions, or the end of file has been reached.
Code:
try{

in = new FileInputStream("users.ini");
} catch(FileNotFoundException e){

return; // if not do nothing
}
First proper debugging, called try and catch, it tries to run the code, if it fails it catches it and runs that code instead, in this case it tries to run the code "in = new FileInputStream("users.ini");" if it fails ie file not found it exits the function.

The file "users.ini" is a standard text file and it is created in you projects root folder (workspace/myLogon2/users.ini)
Clear
Clear does not free up any memory it simply moves our pointer 'count' back to the begining any new additions simply overwrite the users. toString
Both the save and dump, make use to the new USER.toString to write the user to the fail and to write the user to screen showing the ability to re-use code and functions in different situations.
Class myLogon2
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class myLogon {


/**
* @param args
*/

public static void main(String[] args) throws IOException {

int intOption;
boolean running=true;
DATABASE data = new DATABASE();
data.load();

REGISTER register = new REGISTER(data);
LOGON logon = new LOGON(data);

InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader stdin = new BufferedReader( isr );

while(running){

System.out.println("My Logon System 2.0");
System.out.println("-------------------");
System.out.println("Type (1) To add a user");
System.out.println("Type (2) To test a user");
System.out.println("Type (3) To write users");
System.out.println("Type (4) To clear users");
System.out.println("Type (5) To quit app");
intOption = Integer.parseInt(stdin.readLine());
switch(intOption){

case 1:
System.out.println("Add user\n" +
"-----------\n");
System.out.println("Enter Username:");
register.setUsername(stdin.readLine());
System.out.println("Enter Password:");
register.setPassword(stdin.readLine());
System.out.println("Adding user returned "+register.register());
break;
case 2:
System.out.println("Add user\n" +
"-----------\n");
System.out.println("Enter Username:");
logon.setUsername(stdin.readLine());
System.out.println("Enter Password:");
logon.setPassword(stdin.readLine());
System.out.println("Logging on user returned "+logon.logon());
break;
case 3:
data.dump();
break;
case 4:
data.clear();
System.out.println("Users cleared");
break;
case 5:
System.out.println("bye");
running=false;
break;
default:
System.out.println("Input not understood");
}
System.out.println("-------------------");
}
data.dump();
data.save();
}
}
Welcome to our first proper menu, we get the user to input a number because it is easier for the user to type, and easier to check on a switch check. The program also loops for user input until the user chooses to exits "while(running)" 1. The an instance of the DATABASE is created and called 'data'
2. The data.load() tries to load the users from a text file
3. Instances of REGISTER and LOGON are created, data is passed to them (like before)
4. A input reader is created to check the keyboard for, well input!
5. A loop is started, which will run while the boolean (true/false) variable running is set to true.
[repeating]
6. A list of options is display to the user
7. intOption recieves keyboard input
8. switch checks intoption and does what the user requested
IF 1, register
Get username
Get password
Add users
IF 2, logon
Get username
Get password
Add users
IF 3, dump
write a list of users to the screen
IF 4, clear
clear the users, data.clear
IF 5, quit
set running=false, which exits the loop
[back to repeating]
9. save to file
10. exit

Main throws IOException this is because it may inherit an input/output error when calling data.load or data.save, since both these functions can also throw this error.

Add Comment

Help the web master by commenting on the tutorials, thankyou.
Name:
Email: (this will not be shown)
Comment:
  Send email to admin, don't post.

 

Comments

Nobody has commented on this article.
Be the first, the webmaster needs comments good or bad to improve this site.



Copyright (c) 2008, Martin Sykes.
Learning Center is a branch of Martrinex Systems, Martrinex.net
Do not copy any materials from this site without permission from the auther.
Martrinex Learning Center[X]
  Introduction Beginner Intermediate

Important useful well commented source codes
Please read the import tutorial to know how to use them.

Source