Search This Blog

Loading...

Thursday, January 19, 2017

Apache FileUtils Examples.

Apache FileUtils Examples.



General file manipulation utilities.

Facilities are provided in the following areas:

1      Writing to a file.
2      Reading from a file.
3   Make a directory including parent directories.
4   Copying files and directories.
5     Deleting files and directories.
6   Converting to and from a URL.
7      Listing files and directories by filter and extension.
8   Comparing file content.
9    File last changed date.
1    Calculating a checksum.

Maven Repository
                <dependency>
                                                <groupId>commons-io</groupId>
                                                <artifactId>commons-io</artifactId>
                                                <version>2.4</version>
                                </dependency>

Examples.
package swain.swain;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.filefilter.SuffixFileFilter;

public class ApacheFileUtilsExample {

    private static final String PATH = "C:\\appdata\\";

    public static void main(String[] args) throws IOException {

         String fileString = FileUtils.readFileToString(new File(PATH + "file1.txt"));
         System.out.println("Reading file content:" + fileString);
         String fileString2 = FileUtils.readFileToString(new File(PATH + "file2.txt"));
         System.out.println("Reading content:" + fileString2);
         File file1 = new File(PATH + "file1.txt");
         File file2 = new File(PATH + "file2.txt");
         System.out.println("Comparing file content: " + FileUtils.contentEquals(file1, file2));

         FileUtils.copyDirectory(FileUtils.getFile(PATH), FileUtils.getFile(PATH + "copiedNewPath\\"));

         FileUtils.copyDirectory(FileUtils.getFile(PATH), FileUtils.getFile(PATH + "copiedFilterPath\\"), new SuffixFileFilter(".txt"));

         for (File f : FileUtils.getFile(PATH + "copiedFilterPath\\").listFiles()) {
             System.out.println("Contents of copiedFilterPath: " + f.getName());
         }

         File copy = FileUtils.getFile(PATH + "test1.txt");
         FileUtils.copyFile(file1, copy);
         System.out.println("Comparing file content:: " + FileUtils.contentEquals(file1, copy));

         for (File file : FileUtils.getFile(PATH).listFiles()) {
             System.out.println("File Name: " + file.getName());
         }

         FileUtils.deleteDirectory(FileUtils.getFile(PATH + "copiedFilterPath\\"));
         for (File file : FileUtils.getFile(PATH).listFiles()) {
             System.out.println("Contents of PATH after deletion: " + file.getName());
         }

         // Directories
         System.out.println("Temp Dir: " + FileUtils.getTempDirectory().getAbsolutePath());
         System.out.println("User Dir: " + FileUtils.getUserDirectory().getAbsolutePath());

         // Line Iterator
         LineIterator iter = FileUtils.lineIterator(file1);
         while (iter.hasNext()) {
             System.out.println("cmpFile1 lines: " + iter.next());
         }

         // Directory size
         System.out.println("Size of dir: " + FileUtils.sizeOfDirectory(FileUtils.getFile(PATH)) + " bytes.");

         // Ways of writing lines to a file.
         File fileToWrite1 = FileUtils.getFile(PATH + "file1.txt");
         File fileToWrite2 = FileUtils.getFile(PATH + "file2.txt");

         Collection<String> lines = new ArrayList<String>();
         lines.add("Hello world");
         lines.add("First Line");

         FileUtils.write(fileToWrite1, "Written with FileUtils!");
         FileUtils.writeLines(fileToWrite2, lines);

    }
}




Wednesday, January 18, 2017

Java Program: Print Pattern with star java example


To find out multiple example of star print pattern.


Output:



Java code.

package swain.swain;

public class PrintPattern {
public static void example1() {
int space = 0;
for (int i = 5; i >= 1; i--) {
// print first part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print new lint
System.out.println();
space = space + 2;
}

space = 8;
for (int i = 1; i <= 5; i++) {
// print first part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print new lint
System.out.println();
space = space - 2;
}
}

public static void example2() {
int space = 0;
for (int i = 5; i >= 1; i--) {
// print first part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print new lint
System.out.println();
space = space + 2;

}
}

public static void example3() {
int space = 8;
for (int i = 1; i <= 5; i++) {
// print first part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print new lint
System.out.println();
space = space - 2;
}
}

public static void example4() {
int space = 0;
for (int i = 5; i >= 1; i--) {
// print spaces
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print stars
for (int j = 1; j <= i; j++)
System.out.print("* ");

// print new line
System.out.println();
space++;

}
}

public static void example5() {
int space = 4;
for (int i = 1; i <= 5; i++) {
// print spaces
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print stars
for (int j = 1; j <= i; j++)
System.out.print("* ");

// print new line
System.out.println();
space--;

}
}

public static void main(String args[]) {
System.out.println("Example 1");
PrintPattern.example1();
System.out.println("Example 2");
PrintPattern.example2();
System.out.println("Example 3");
PrintPattern.example3();
System.out.println("Example 4");
PrintPattern.example4();
System.out.println("Example 5");
PrintPattern.example5();
}
}

Thursday, January 12, 2017

Java Program: Basal Metabolic Rate (BMR) Calculator .

Basal metabolic rate (BMR), is the rate of metabolism that occurs when an individual is at rest in a warm environment and is in the post absorptive state, and has not eaten for at least 12 hours.

Find below java program.









package swain.swain;

import java.util.Scanner;

public class BMR {
public static void main(String[] args) {
int age;

double weight, height, BMRw, BMRm;

System.out.println("Enter weight in lbs:");

Scanner kb = new Scanner(System.in);

weight = kb.nextDouble();

System.out.println("Enter height in inches:");

height = kb.nextDouble();

System.out.println("Enter age in years:");

age = kb.nextInt();

BMRw = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age);

BMRm = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age);

System.out.println("BMR for woman is: " + BMRw);

System.out.println("BMR for man is: " + BMRm);

System.out.println("A typical Chocolate Bar contains about 230 calories");

System.out.println("No. of Chocolate Bars consumed to maintain your weight: ");

int choco = 230;

System.out.println(Math.round(BMRw / choco));
System.out.println(Math.round(BMRm / choco));
}
}

Wednesday, January 11, 2017

Java Program : How to find the LOVE percentage calculator between a boy and a girl.

It is a Fun Love calculator  algorithm to find out love percentage. It is only for fun.

You can check FLAMES Game.



Here is Java program.


package swain.swain;

import java.util.ArrayList;
import java.util.List;

public class LoveCalculator {
private static List<String> getCount(String fname, String sname) {
List<String> list = new ArrayList<String>();
String love = "Love";
String name1 = fname;
String name2 = sname;
for (int i = 0; i < name1.length(); i++) {
String temp = name1.charAt(i) + "";

if (list.contains(temp)) {
int indexOfElement = list.indexOf(temp);
int prevCount = Integer.parseInt(list.get(++indexOfElement).toString());
prevCount++;
String newCount = (prevCount) + "";
list.set(indexOfElement, newCount);
continue;
}

list.add(temp);
list.add("1");
}

for (int i = 0; i < name2.length(); i++) {
String temp = name2.charAt(i) + "";

if (list.contains(temp)) {
int indexOfElement = list.indexOf(temp);
int prevCount = Integer.parseInt(list.get(++indexOfElement).toString());
prevCount++;
String newCount = (prevCount) + "";
list.set(indexOfElement, newCount);
continue;
}

list.add(temp);
list.add("1");
}

for (int i = 0; i < love.length(); i++) {
String temp = love.charAt(i) + "";

if (list.contains(temp)) {
int indexOfElement = list.indexOf(temp);
int prevCount = Integer.parseInt(list.get(++indexOfElement).toString());
prevCount++;
String newCount = (prevCount) + "";
list.set(indexOfElement, newCount);
continue;
}

list.add(temp);
list.add("1");
}
List<String> result = new ArrayList<String>();

for (int i = 1; i < list.size(); i += 2) {
result.add(list.get(i));
}
return result;
}

private static int getLovePercentage(String fname, String sname) {
List<String> count = getCount(fname, sname);
if (count.size() == 1) {
String result = count.get(0).toString() + "";
return Integer.parseInt(result);
}

if (count.size() == 2) {
String result = count.get(0).toString() + count.get(1).toString();
return Integer.parseInt(result);
}

do {
List<String> sub = new ArrayList<String>();
int size = count.size() / 2;
for (int i = 0; i < size; i++) {
String newC = (Integer.parseInt(count.get(i).toString()) + Integer.parseInt(count.get(count.size() - 1 - i).toString())) + "";

if (newC.length() == 2) {
sub.add((newC.charAt(0) + ""));
sub.add((newC.charAt(1) + ""));
} else {
sub.add(newC);
}
}

if ((size * 2) != count.size())
sub.add(count.get(size));

count = new ArrayList<String>();
count = sub;
} while (count.size() != 2);

String result = count.get(0).toString() + count.get(1).toString();
return Integer.parseInt(result);
}

public static String getLovePercentageResult(String fname, String sname) {
int per = getLovePercentage(fname, sname);
String result = "Love Percentage Between " + fname + " And " + sname + " is " + per + "% ";

return result;
}

public static void main(String args[]) {
System.out.println(LoveCalculator.getLovePercentageResult("Rama", "Sita"));
}
}


Output:


Java Program : How to find the relation between a boy and a girl using FLAMES.

It is really a fun game. Below find out Java code for this game.


You can check LOVE Calculator  .


Here is program.


package swain.swain;

public class Flames {

public static String getMatchResult(String fname, String sname) {
String firstName, secondName;
if (fname != null & sname != null) {
firstName = fname.trim().toLowerCase();
secondName = sname.trim().toLowerCase();
String firstNames[] = firstName.split(" ");
String secondNames[] = secondName.split(" ");
firstName = "";
secondName = "";
for (int i = 0; i < firstNames.length; i++) {
firstName = firstName + firstNames[i];
}
for (int i = 0; i < secondNames.length; i++) {
secondName = secondName + secondNames[i];
}
int length = secondName.length() + secondName.length();
boolean namecheck[] = new boolean[secondName.length()];
for (int i = 0; i < secondName.length(); i++) {
namecheck[i] = false;
}
for (int i = 0; i < firstName.length(); i++) {
for (int j = 0; j < secondName.length(); j++) {
if ((namecheck[j] == false) && (firstName.charAt(i) == secondName.charAt(j))) {
namecheck[j] = true;
length = length - 2;
break;
}
}
}
boolean flamescheck[] = new boolean[6];
for (int i = 0; i < 6; i++) {
flamescheck[i] = true;
}
int count = 6;
int k = 1, deleted_letters = 0;
int j;
for (j = 0; j <= count; j++) {
if (k <= length) {
if (j == count) {
j = 0;
}
if (flamescheck[j] == true) {
k = k + 1;
}
}
if ((k - 1) == length) {
deleted_letters = deleted_letters + 1;
flamescheck[j] = false;
k = 1;
}
if (deleted_letters == 6) {
if (j == 0) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are good FRIENDS";
} else if (j == 1) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are LOVERS";
} else if (j == 2) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " have alot of AFFECTION";
} else if (j == 3) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are MARRIED";
} else if (j == 4) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are ENEMIES";
} else if (j == 5) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are SIBLINGS";
}
break;
}
}
}
return null;
}

public static void main(String args[]) {
System.out.println(Flames.getMatchResult("Rama", "Sita"));
}
}

Output:

How to convert JSON file to String

Below method will return String. You need to pass argument file path.


public static String getStringFromInputStream(String filepath) {

         BufferedReader br = null;
         StringBuilder sb = new StringBuilder();

         String line;
         try {
             br = new BufferedReader(new FileReader(filepath));
             while ((line = br.readLine()) != null) {
                 sb.append(line);
             }

         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (br != null) {
                 try {
                      br.close();
                 } catch (IOException e) {
                      e.printStackTrace();
                 }
             }
         }

         return sb.toString();


    }