Read/Write Files

To read in from and file and also output to a file, java uses streams to “talk” to the files. These streams allow for communicating with different stream conversion tools, the object tool within this tutorial is the DataInputStream which “talks” to the FileInputStream.

I have attached the code within a zip file with the required input file as well.

Below is the code

import java.io.*;
 
class javareadfile
{
       public static void main(String args[])
       {
              String fileName = "country.txt";//input file
              String outFileName = "sqljavacountry.txt";//output file
 
              try
              {
                     // file input stream, basically a pointer to the stream of the input file
                     FileInputStream fStream = new FileInputStream(fileName);
                     // file output stream, basically a pointer to the stream for outputing data
                     FileOutputStream fOutStream = new FileOutputStream(outFileName);
 
                     // the input/output data streams that connect to the above streams
                     DataInputStream dInput = new DataInputStream(fStream);
                     DataOutputStream dOutput = new DataOutputStream(fOutStream);
 
                     // whilst there is data available in the input stream
                     while (dInput.available() !=0)
                     {
                            String in = dInput.readLine();// read a line from the input file
                            // output a stream of data to the output file
                            dOutput.writeBytes("insert into country(place) values (\""+in+"\");\n");
                     }
                     //close the two files.
                     dInput.close();
                     dOutput.close();
              }
              catch (Exception e)// incase of any errors
              {
                     System.err.println("There was a error : " + e.toString());
              }
       }
}

If you save this as javareadfile.java and also create a countrys.txt file with what ever text you like, e.g.

United Kingdom
France
Germany
United States
etc.

Once you have compiled the program (javac -deprecation javareadfile.java, may have to use -deprecation if using java virtual machine 1.5 over 1.4) and execute the program (java javareadfile), it will look for the file countrys.txt within the same directory as the program executable and also create outcountrys.txt within the same directory (it will write over the file if there is one present). Then within the while loop it will read the input file line by line and output to the screen what has been read and also output to the output file.

Of course to finish off to close down the files and return back to the console.

Hello world ! classic

This is the classic hello world tutorial for java, to get the java compiler and also the run-time environment you will need to goto the Java (Sun). The compiler (javac) compiles into java byte code, which means that this code is able to run on any OS with the java run-time environment (aka virtual machine).

If you save this

public class helloworld
{
	public static void main(String[] args)
	{
		System.out.println("Hello world");
	}
}

as helloworld.java

and then from the command line

javac helloworld.java

this will create the helloworld.class which is the java byte code, to run the byte code.

java helloworld

and hopefully there will be

Hello world

on the console.

C++ DLL Objects accessed from C#

Because there is a few things that c# cannot do compared to c++, e.g. cpu/memory management. And also there is probably allot of dll’s out there are still required for some events, c# is able to communicate with these files and use there functions within the c# language.

To create an dll within Visual Studio 2005 within the language c++, if you do the following

1. New project -> c++ -> empty project
2. Enter project name (e.g. hellocdll)
3. Right click source files ( in the solution explorer) add-> new item
enter an cpp filename.
4, Right click on the main project heading in the solution explorer -> properties
configuration properties->general inner screen project defaults -> configuration type, alter to dynamic library (.dll)
5. Copy and paste code and then compile.

#include <stdio.h>
 
extern "C"
{
  __declspec(dllexport) void DisplayMessageFromDLL()
  {
              printf ("Hi From the C DLL!\n");
  }
 
  __declspec(dllexport) int DisplayValueAndReturn(int i)
  {
         printf("Value %i\n", i);
         return i+2;
  }
}

The extern “C” means that the references within the code are going to be available externally and marco __declsepc(dllexport) is for the MS compile to inform that functions are to be available within an dll file.

To create an c# project to communicate with the above dll

1. New project -> c# -> empty project
2. Enter project name (e.g. hellodlltest)
3. Right click on the project name ( in the solution explorer) add-> new item
select class and enter a filename
4. Copy and paste the code and then compile. (you may need to change the Dllimport to the dll file name that has been created from the c dll project)

using System;
using System.Runtime.InteropServices;     // DLL support
 
namespace hellodlltest
{
    class hellodllC
    {
        [DllImport("hellocdll.dll")]
        public static extern void DisplayMessageFromDLL();
 
        [DllImport("hellocdll.dll")]
        public static extern int DisplayValueAndReturn(int i);
 
        static void Main ()
           {
                  Console.WriteLine ("C# program 'talking' to an C DLL");
            DisplayMessageFromDLL();
            Console.WriteLine(DisplayValueAndReturn(3).ToString());
           Console.ReadLine()
           }
    }
}

5. Copy the dll file from the debug directory of the c++ created dll project and place into the created bin/debug directory for this c# project

Operator

The standard class function are not able to utilize the standard operators within the c# language, for example the multiple, add, subtraction and divide in a mathematics example.

To overcome this problem, there is a ‘operator’ special syntax that allows for this to take place. The operator can work with any of the c# language standard functions of which you are able to program there functional aspects within the class. The syntax for this is

public static <return type> operator <operator type>(<parameter list of passed variables>);

for example if there was an return type of int and two integer values passed in the parameter list and using the addition operator.

public static int operator +(int a, int b)

Below is some code that will demonstrate this further within a general code development.

using System;
 
class operatorBase
{
       private int i;       // private member of the class
 
       public operatorBase() 
       {
              i = 0;       
       }
 
       public operatorBase(int init)  
       {
              this.i = init; 
       }
 
       // get and set the value for the private member i
       public int Value
       {
              get { return i;}
              set { i = value;}
       }
 
       // the operator +, parameters are the two values that you want to add, can be overloaded with different values
       // e.g. (int i2, int i3) for example.
       public static operatorBase operator +(operatorBase i2, operatorBase i3)
       {
              // create the return;
              operatorBase locali= new operatorBase();
              locali.i = i2.i + i3.i;  have access to the internals of passed parameters
              return  locali;       // return the operatorBase class
       }
}
 
class operatorTest
{
 
       public static void Main()
       {
              operatorBase opBase = new operatorBase();
 
              // set the value to 3 and also output the value;
              opBase.Value = 3;
              Console.WriteLine(opBase.Value);
 
              operatorBase opBase2 = new operatorBase(4);
 
              // to add to the operatorbases together, but will return an operatorBase, thus bracket the equation and use the .Value to get the value. 
              Console.WriteLine((opBase + opBase2).Value);
 
              // since creating two new on the fly operatorBase, then the result is an int value again.
              Console.WriteLine((new operatorBase().Value = 3) + (new operatorBase().Value = 2));
       }
}

Yielding results

Yield is a new syntax word within the .net 2 language. This allows for the IEnumerable interface to have direct interaction instead of using the IEnumerator interface to iterate though a result set. For easier demonstration, I think, the code examples, the first code is a .net 1 version of the interface IEnumerable.

using System;
using System.Collections;
 
// the inital class is IEnumerable- means that it has to implement the GetEnumerator
public class Class : IEnumerable 
{
       // internal class to implement the IEnumerator interface, which inturn has to do the MoveNext, Current, Reset methods.
       private class ClassEnumerator : IEnumerator
       {
              // internal values to go through the array
              private int index = -1;
              private Class P;
              // setup the internal variable
              public ClassEnumerator(Class P) 
              {
                     this.P = P; 
              }
              // move within the array, if any values are present.
              public bool MoveNext()
              {
                     index++;
                     return index < P._Names.Length;
              }
              // set the internal to -1, thus restart
              public void Reset() 
              { 
                     index = -1;
              }
 
              // get the Current object
              public object Current 
              { 
                     get 
                     { 
                            return P._Names[index]; 
                     } 
              }
       }
 
       // return a IEnumerator object of the above with itself passed
       public IEnumerator GetEnumerator()
       {
              return new ClassEnumerator(this);
       }
 
       // the internal string array of names
       private string[] _Names;
       // the new class setup process, 
       public Class(params string[] Names)
       {
              _Names = new string[Names.Length];
              // copy the passed parameter starting at position 0
              Names.CopyTo(_Names,0);
       }
}
 
class ClassProgram
{
       static void Main(string[] args)
       {
              Class ClassArr = new Class("Student1", "Student2","Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

This is able to output a string of

Student1
Student2
Studentx

Since the Class class (it is a class of students), there is allot of code to iterate with the foreach function.

Within .net 2 there is a nice and more tighter method called yield, an yield will yield a result and be able to iterate though a result set with the IEnumerable return set. Again, here is the source code.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       static void Main(string[] args)
       {
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

Far less code and also the result is exactly the same.

Also there are other benefits of the yield attached to an IEnumerable interface, here is some more code to demonstrate how to implement a power function to display the power result being built up. This demonstrates how to use just a single method to return an iterate-able result.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       // IEnumerable linked to yield is new in .net 2, it allows for the 
       // iteration of this method, acting like array instead of a single return.
       public static IEnumerable Power(int number, int exp)
       {
              int counter = 0, result = 1;       // setup the default values.
              while (counter++ < exp)              // increament counter and whilst lower than the passed parameter exp
              {
                     result *= number;       // result = result * number;
                     yield return result;       // yield the result and return
              }
       }
 
       // can also just iterate though a array of strings (in this example)
       public static IEnumerable StReturn(params string[] names)
       {
              int counter = -1;
              while (counter++ < (names.Length-1))
                     yield return names[counter];
       }
 
       static void Main(string[] args)
       {
              // can do a return of a power function as well
              foreach(int e in Power(4,3))
                     Console.WriteLine(e.ToString());
 
              // you can just iterate a string 
              string[] st = {"student1","student2","studentx"};
              foreach(string s in StReturn(st))
                     Console.WriteLine(s.ToString());
 
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

I have also include the code from above to demonstrate the similar usage for iterate though a string array.

Output would be

4
16
64
student1
student2
studentx
Student1
Student2
Studentx

You will need to have .net 2 installed or mono (use the gmcs part of mono to use the .net 2 functions.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

using System;
 
// create a class with a generic type of T (e.g. pass in the type of your choice
public class GenTest<T>;
{
       // the private value
       private T genericValue;
 
       // default constructor for the class (same name as the class)
       // ~ is the deconstructor
       public GenTest(T generic) 
       {
              genericValue = generic;       // set the internal T = passed value
       }
 
       // return the value of the internal value
       public T ReturnValue()
       {
              return genericValue;
       }
}
 
public class MainProgram
{
       static void Main()
       {
              // create a integer type class, with the default value of 2
              GenTest<int> genInt = new GenTest<int>(2);
              Console.WriteLine("Int generic = " + genInt.ReturnValue());
 
              // same class create a string with the default value of "cool"
              GenTest<string> genString = new GenTest<string>("cool");
              Console.WriteLine("String generic = " + genString.ReturnValue());
       }
}

If you save the code and run with .net 2 or greater (.NET Framework) ( since this was part of .net 2 and not with .net 1). The output will be

Int generic = 2
String generic = cool

As you can see the same class is able to use both integer and strings as the default variable type.

Collections – ArrayList

Collections – ArrayList, the ArrayList is part of the Collections namespace. The ArrayList acts as the same as the array (Array Example) apart from it allows other functional aspects to access the list of array.

Shall comment more on the different aspects in later tutorials, but basically there many different parts to a class that allow for better functionality e.g
1. Interfaces = base of a class for strict implementation)
2. IEnumerable (which is a interface) = means that you implement GetEnumerator aspects of a class, e.g. for the foreach command)
3. Generics (which is part of .net 2) = Similar to templates (Generics) in c++ and also generics from Java).
4. Etc. shall comment more on these.

This is the code

using System;
 
namespace ArrayListTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            arrayList.Add(2);
            arrayList.Add(3);
            arrayList.Add("hi there");
 
            foreach (object obj in arrayList)
                Console.WriteLine(obj.ToString());
        }
    }
}

If you save as arraylisttest.cs, and then run, the output will be

2
3
hi there

It basically allows you to add in any object into the ArrayList, and since objects have the ToString() function, then it is able to print out the object, of course custom made objects will either display there type or the ToString() will have to be implemented.