How To Use Java Packages In .NET

Introduction

This article describes how to use Java Packages in .NET using IKVM.NET. In my previous article , I briefly described IKVM.NET. So before reading this tip, you can refer to that one. IKVM.NET uses the OpenJDK Project.

How to Do This

To use the IKVM.NET library, first of all you need to download it from here. After downloading IKVM.NET, unzip the file. You will see the following folders and files in the unzipped file.

1.png
 

 

Now suppose you are creating a project in C#.NET and you want to use Java packages in this project, then we need to add a reference for the required package. For each package, there is a separate DLL file so you can add any package.

Here, I will use the GZIP Compression class present in the Java.util.zip package of Java. I know all of you are asking why am I using GZIP compression of Java when it is present in .NET already. The reason behind that is that the GZIP compression provided by Java is better than .NET.

Let's see how to use it. So here we add "IKVM.OpenJDK.Util.dll" and "IKVM.OpenJDK.Code.dll" because the "GZIPOutputStream" class is present in the "IKVM.OpenJDK.Util" package and the FileInputStream class required for file manipulation is present in Java.io that resides in the "IKVM.OpenJDK.Core" package.

using java.io;
using java.util.zip;namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string srcfile="c:\\source.txt";
            string dstfile="c:\\destination.txt"; 
            FileInputStream fin = new FileInputStream(srcfile);
            GZIPOutputStream fout = new GZIPOutputStream(new FileOutputStream(dstfile)); 
           byte[] buffer = new byte[1024];
            int bytesRead;            while ((bytesRead = fin.read(buffer)) != -1) //srcfile.getBytes()
            {
                System.Console.WriteLine(bytesRead);
                fout.write(buffer, 0, bytesRead);            }            fin.close();
            fout.close();
                  }     }
} 

So as you can see in the code above, by using IKVM.NET, we can use any Java package very easily without any overhead. You can use the same code that you have used in Java.

Summary

You can use many powerful facilities that are provided by Java packages, without any overhead. In this tip, I am using a very simple utility of Java but if you want, you can use it accordingly and find it more useful later on.

References

http://www.ikvm.net/


Similar Articles