List TNS entries from TNSNAMES.ORA using java

I was searching for the java program which should List TNS entries from TNSNAMES.ORA using java. I Google this but not found any satisfactory answer. So I have written the below code to list the tns entries from TNSNAMES.ORA file.

  • What is TNSNAMES.ORA? TNSNAMES.ORA is a SQL*Net configuration file that defines databases addresses for establishing connections to them.
  • Requirement to Run this Program: To successfully run this program ORACLE_HOME parameter should be set in the Environmental Variables.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TNSNamesList {
	
	public static void main(String[] args) 
	{
		
		BufferedReader br = null;
		String pattern = "^([^#()\\W ][a-zA-Z0-9.]*(?:[.][a-zA-Z]*\\s?=)?)"; //Regular Expression Pattern for TNS Alias
		Pattern r = Pattern.compile(pattern);
		 
		try 
		{
 
			String sCurrentLine; 
			br = new BufferedReader(new FileReader(System.getenv("ORACLE_HOME")+"\\NETWORK\\ADMIN\\TNSNAMES.ORA")); 
			while ((sCurrentLine = br.readLine()) != null) 
			{
				//System.out.println(sCurrentLine);
				Matcher matcher = r.matcher(sCurrentLine);
				if(matcher.find())
				{					
					System.out.println(matcher.group().toUpperCase());				
				}
			}
 
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
			try 
			{
				if (br != null)br.close();
			} 
			catch (IOException ex) 
			{
				ex.printStackTrace();
			}
		}
	}	
}
List TNS entries from TNSNAMES.ORA using java
Tagged on:     

One thought on “List TNS entries from TNSNAMES.ORA using java

  • March 17, 2016 at 11:52 am
    Permalink

    tnsnames.ora-Connections can actually have _ or . in their name 🙂

    Reply

Leave a Reply