Posts

Showing posts with the label Java

Parsing xml node tags using documentbuilderfactory

package test; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class xmlTest { public static void main(String[] args) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("filePath"); NodeList nlist = doc.getElementsByTagName("param"); System.out.println(nlist.getLength()); for(int ent=0; ent<nlist.getLength(); ent++){ System.out.println(doc.getElementsByTagName("param").item(ent).getTextContent()); } } }

Folders in any given directory

import java.io.File; import java.util.ArrayList; import java.util.List; public class FilesinDir { public static void main(String[] args) { File f = new File("C:\\path"); File[] fl = f.listFiles(); boolean flag = false; List<String>folder = new ArrayList<String>(); for(File f2: fl) { String s = f2.getName(); for(int i = 0; i<s.length(); i++) { if(s.charAt(i)=='.') { flag = false; }else { flag = true; } } if (flag==true){ folder.add(s); } } System.out.println("total number of folders are::"+folder.size()); System.out.println("folders in dir are::"+ folder); } }

Convert decimal to binary and then convert to inverse of binary by changing 0 to 1 and 1 to 0

public class test { public static void main(String[] args) { System.out.println(getIntegerComplement(50)); } static int getIntegerComplement(int n) { String binary = ""; String rev =""; StringBuilder sb = new StringBuilder(); int k; while(n>0){ int r= n%2; binary = r+binary; n= n/2;         } System.out.println("binary for n is::"+ binary); for(int i=0; i<binary.length(); i++) { sb.append(binary.charAt(i)); if(sb.charAt(i)=='0') { sb.replace(i, i+1, "1"); }else{ sb.replace(i, i+1, "0");         } } rev = sb.toString(); k = Integer.parseInt(rev); int decimal=0; int power=0; int l=k; while(l>0) { int tmp = l%10; decimal = (int) (decimal+ tmp*Math.pow(2, power)); l=l/10; power++; } System.out.println("decimal of inverse is:::"+ decimal); System.out.print("inverse binary of n is:::")...

How to generate string with given range.

Say there is drop down list to select range e.g. 1-9 and based on that range you need to input value in text field having length equal to range. public class testlength { public static String test(int idgit) { String s = null; Random m = new Random();       // take a temp string and initialize it randomly or hardcoded it String temp = "5" //Integer.toString(m.nextInt(8)); for(int i=1; i<idgit+k;i++) { int j= m.nextInt(8);     s = Integer.toString(j);     temp = temp+s; } return temp; }