C# use using Statement to define its scope outside of which an object or objects are disposed. But there is no equivalent syntax statement in Java. CodePorting C#2Java engine intelligently translates the C# code and handle this situation by producing try/catch block in java code. This Technique converts C# code to java code with same formatting ready to be complied.
Following example shows migration of C# using statement in java:
C# Code:
using System.IO;
namespace CsPorter.Tests.Convert.LanguageConstructs.UsingStatement
{ public class Test2
{ void Method()
{
//some comments (vertical indent)
using (Stream stream = new FileStream("nowhere", FileMode.Open)) { stream.ReadByte();
}
//horisontal indent
using (Stream stream = new FileStream("nowhere", FileMode.Open)) { stream.ReadByte();
}
}
}
}
Java code generated by CodePorting:
package CsPorter.Tests.Convert.LanguageConstructs.UsingStatement;
// ********* THIS FILE IS AUTO PORTED FORM C# USING CODEPORTING.COM *********
import com.codeporting.csharp2java.System.IO.Stream;
import com.codeporting.csharp2java.System.IO.FileStream;
import com.codeporting.csharp2java.System.IO.FileMode;
public class Test2
{ private void method() throws Exception
{
//some comments (vertical indent)
Stream stream = new FileStream("nowhere", FileMode.OPEN); try /*JAVA: was using*/
{ stream.readByte();
}
finally { if (stream != null) stream.close(); }
//horisontal indent
Stream stream1 = new FileStream("nowhere", FileMode.OPEN); try /*JAVA: was using*/
{ stream1.readByte();
}
finally { if (stream1 != null) stream1.close(); } }
}
It is clear from above example that CodePorting C#2Java engine automatically generated the try/catch code to handle the using statement.