java to Java Learn programming Java

Lesson:

File Management


Exercise:

java to Java 55


Objetive:

Create a basic java to Java translator.

It must accept a java source files, and create an equivalent Java source file. It will receive the file name in the command line, and it must translate at least:

"Main()" into "main( String[] args )"
"string" into "String"
"bool" into "boolean"
"Console.WriteLine" into "System.out.println"
" : " into " extends " if it is in the same line as the word "class" (and any further improvements you may think of, such as strings handling, or converting a ReadLine to a try-catch block).


Code:

import java.util.*;
public class CsharpToJava
{
	public static void main(String[] args)
	{
		String line;
		String name;

		if (args.length < 1)
		{
			name = new Scanner(System.in).nextLine();
		}
		else
		{
			name = args[0];
		}

		java.io.FileReader iFile = new java.io.FileReader(name);
		java.io.BufferedReader iFileBufferedReader = new java.io.BufferedReader(iFile);
		java.io.FileWriter oFile = new java.io.FileWriter(name + ".java");

		do
		{
			line = iFileBufferedReader.readLine();

			if (line != null)
			{
				line = line.replace("bool ", "boolean ");
				line = line.replace("string ", "String ");
				line = line.replace("Console.WriteLine", "System.out.println");

				oFile.write(line + System.lineSeparator());
			}

		} while (line != null);

		iFile.close();
		oFile.close();
	}
}