Java Demo Program 2
See the notes at the bottom of the page, after the program listing...
import java.io.*; // Import the Input and Output Stream Classes
import java.util.Vector;
import java.util.StringTokenizer;
public class JavaDemo2{
public int getNumValue(String str)
{
Integer tempInt;
int startPos;
String numString = new String();
String trimmedString;
String tempStr = "this is a line with strings and a number";
startPos = tempStr.length();
numString = str.substring(startPos);
trimmedString = numString.trim(); //trims whitespace from both ends
System.out.println("Number is " + trimmedString);
tempInt = Integer.valueOf(trimmedString);
return tempInt.intValue();
}
public Vector getIntVector(String str)
{
StringTokenizer tokens = new StringTokenizer(str);
String tempStr;
Vector tempVector = new Vector(tokens.countTokens());
Integer tempInteger;
while (tokens.hasMoreElements())
{
tempStr = tokens.nextToken();
tempInteger = new Integer(tempStr);
tempVector.addElement(tempInteger);
}
return tempVector;
}
public void printVector(Vector intVector)
{
int i;
Integer tempInteger;
for(i = 0; i < intVector.size(); i++)
{
tempInteger = (Integer)intVector.elementAt(i);
System.out.print("" + tempInteger.intValue() + " ");
}
System.out.println();
}
public static void main(String[] args){
String infileName = new String("sampleFile.txt");
String outfileName = new String("sampleFileOut.txt");
String sample = new String("String+nulls\0\0\0\0\0");
char sample2[] = new char[80];
int numValue;
boolean arrayNumbers=false;
Vector intVector;
sample2 = ("Another string with nulls:\0\0\0\0\0\0\0\0\0").toCharArray();
System.out.println("String with null: " + sample + " characters");
System.out.println("Another sample with nulls: " +
String.copyValueOf(sample2));
JavaDemo2 testRun = new JavaDemo2();
try{
BufferedReader infile =
new BufferedReader(new FileReader(infileName));
// Open for reading
System.out.println("File open for reading...");
BufferedWriter outfile =
new BufferedWriter(new FileWriter(outfileName));
// Open for writing
System.out.println("File open for writing...");
String line;
while((line = infile.readLine()) != null)
{
System.out.println(line); // routes output to CRT
if (line.startsWith("this is a line with strings and a number"))
{
numValue = testRun.getNumValue(line);
System.out.println("This line has the number: " + numValue);
}
if (arrayNumbers)
{
intVector = new Vector();
intVector = testRun.getIntVector(line);
System.out.print("Here's the array: ");
testRun.printVector(intVector);
}
if (line.startsWith("5 more numbers:"))
arrayNumbers = true;
else arrayNumbers = false;
outfile.write(line, 0, line.length()); // routes output to file
outfile.newLine();
}
System.out.println("Done copying file...");
infile.close();
outfile.close();
System.out.println("Files closed.");
}
catch(IOException e){
System.err.println(e);
return;
}}}
Notes about the above program:
- Two of the special classes that this program uses are: Vector and StringTokenizer
These two classes are in the java.util package and are "imported" at the top of
the program
- First look at main(). Three strings are initialized using the format:
String stringname = new String("stringvalue");
- An alternative format that is special for Strings is:
String stringname = "stringvalue";
With this version, "new String()" is automatically invoked by Java
- Character arrays are initialized with the format:
char sample2[] = new char[80]; allocating space for 80 characters.
Note: in Java, character arrays do not end in the null char as in C and C++
- In a character array (but not in a String), values can be added separately:
char[0]='A'; char[1]='B'; etc.
- Character arrays can also be initialized from Strings, using the toCharArray
() method:
sample2 = ("This is a string").toCharArray();
OR: String str = "Hello world";
sample2 = str.toCharArray();
- An instance of class JavaDemo2 is created:
JavaDemo2 testRun = new JavaDemo2()
This allows access to the functions defined outside of main()
- For instance, to call the getIntArray() function, the syntax is:
testRun.getIntArray(line); //Converts a string of numbers into an integer Vecto
r
- If the function is declared as static:
public static Vector getIntArray(String str)...
The function call would be simply: getIntArray(line)
- The program reads a text file line by line, where each line is a String
The String is read using the method readLine():
line = infile.readLine()
- The try-catch block is only necessary here because we are reading/writing to
a file. If there is a problem opening the file, an exception will be "throw
n"
and "caught" by the catch block.
- Use the class String's startsWith() method to parse a command line into
a command and a number following the command. (Like: LOAD 0)
- The syntax for startsWith() is:
if (line.startsWith("String value")) ...
For more information on methods available in the String class, see the Java API
site
- This program demonstrates using the Vector class to contain a collection
of Integer's. Note that class Integer is different from int.
Look at the Java API site for more info about class Integer.