Sunday, May 31, 2009

How to read Properties file in Java using ResourceBundle and Properties class

There are many ways to read properties file in java. Here explained two way, using

1. ResourceBundle
2. Properties Class
3. How to write properties file is also mentioned in ReadPropFile.java

How to use this tutorial
1. Create one directory src and put both below files (MyProp.properties and ReadPropFile.java)

2. MyProp.properties
name = Binod Kumar Suman
roll = 110
city = Bangalore

3. ReadPropFile.java

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;


public class ReadPropFile {

public static void main(String[] args) {
// readpropFile();
otherway();
}

public static void readpropFile(){
ResourceBundle bundle = ResourceBundle.getBundle("MyProp");
String studentName = bundle.getString("name");
String roll = bundle.getString("roll");
System.out.println("Student Name :: "+studentName);
System.out.println("Roll Number :: "+roll);

// Fetch all the Properties.

Enumeration keys = bundle.getKeys();
while(keys.hasMoreElements()){
System.out.println(keys.nextElement());
}

}

public static void otherway(){
try{
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream("src/MyProp.properties"));
String studentName = propertiesFile.getProperty("name");
String roll = propertiesFile.getProperty("roll");
System.out.println("Student Name :: "+studentName);
System.out.println("Roll Number :: "+roll);

//Fetch all the Properties.

String key;
Enumeration e = propertiesFile.propertyNames();
while (e.hasMoreElements()) {
key = (String)e.nextElement();
System.out.println(key+" "+propertiesFile.getProperty(key));
}

// Write to properties file
propertiesFile.setProperty("Compnay","Satyam");
propertiesFile.store(new FileOutputStream("src/MyProp.properties"),null);


}catch(IOException e){
e.printStackTrace();
}
}
}

Saturday, May 23, 2009

How to read file in Java

Put both java file and Myfile.txt file in same folder.


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class ReadFile {

public static FileReader reader;
public static BufferedReader br;

public static void main(String[] args) {
try {
reader = new FileReader("MyFile.txt");
br = new BufferedReader(reader);
String data="";

while((data = br.readLine())!= null){
System.out.println(data);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to write file in Java

Put both java file and Myfile.txt file in same folder.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {

public static FileWriter writer;
public static BufferedWriter bw;

public static void main(String[] args) {
try{
writer = new FileWriter("MyFile.txt",true);
// writer = new FileWriter("src\\MyFile.txt"); For every time new file.

bw = new BufferedWriter(writer);
bw.write("\n");
bw.write("WRITTING some thing");
bw.close();
System.out.println("Check your file");
}catch(FileNotFoundException e){ e.printStackTrace(); }
catch(IOException e){ e.printStackTrace(); }
}
}

How to get IP Address by Java

import java.net.InetAddress;
public class GetIPAddress {

public static void main(String[] args) {
String ip = "";
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ip = inetAddress.getHostAddress();
System.out.println("IP Address :: "+ip);
} catch (Exception e) {
e.printStackTrace();
}
}

}

Thursday, May 14, 2009

How to get other TimeZone time by JAVA

You can get any timezone time just you should have the timezone ID. Here I gave two methods.
1. How to get all timezone ID.
2. How to get time of any timezone ID.
Both methods are in the same java file (OtherTimeZoneTime.java)


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class OtherTimeZoneTime {

public static void main(String[] args) {
String timeZoneId = "America/Chicago";
getTime(timeZoneId);
// getAllTimeZone();
}

public static void getAllTimeZone() {
String[] zoneIds = TimeZone.getAvailableIDs();
for (int i = 0; i < zoneIds.length; i++) {
TimeZone tz = TimeZone.getTimeZone(zoneIds[i]);
System.out.println(tz.getID() + " " + tz.getDisplayName());
}
}

public static void getTime(String timeZoneId) {
Calendar calTZ = new GregorianCalendar(TimeZone.getTimeZone(timeZoneId));
calTZ.setTimeInMillis(new Date().getTime());
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, calTZ.get(Calendar.YEAR));
cal.set(Calendar.MONTH, calTZ.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, calTZ.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, calTZ.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, calTZ.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, calTZ.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, calTZ.get(Calendar.MILLISECOND));
System.out.println(cal.getTime());
}
}

Some timeZoneId :
Asia/Calcutta
Europe/Vatican
Asia/Istanbul
Australia/Darwin
Australia/Melbourne
Australia/Sydney
America/Cordoba
America/Fortaleza
America/Godthab
America/Jujuy
America/Maceio

Tuesday, May 12, 2009

How to backup of your blogger blog

There are many ways to take your blog backup. Even some tools are also available in market. But here I explain two ways:

1. Write one simple java program and take many blog backup together with timestamp.
2. Use Export and Import facility of blogger

1. Write one simple java code (BlogBackup.java)


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BlogBackup {
public static String repo = "E:\\Blog_BACKUP\\";
public static String ext = ".xml";
public static String url1 = "http://your_blogName _1.blogspot.com/feeds/posts/default?max-results=1000";
public static String url2 = "http://your_blogName _2.blogspot.com/feeds/posts/default?max-results=1000";
public static String url3 = "http://your_blogName _3.blogspot.com/feeds/posts/default?max-results=1000";

public static void main(String[] args) {
takeBackup();
}
public static void takeBackup(){
String folderName = createFolder();
String[] url = {url1,url2,url3};
try {
for(int i=0;iString fileName = folderName+"\\"+getFileName(url[i]);
doDownload(url[i],fileName);
System.out.println("Completed :: "+fileName);
}
} catch (IOException e) {e.printStackTrace();}
}
public static String getFileName(String url){
String fileName = url.substring(url.indexOf("//")+2,url.indexOf("."));
Format formatter = new SimpleDateFormat("MMM-dd-yyyy-HH-mm");
String now = formatter.format(new Date());
return fileName+"_"+now+ext;
}
public static String createFolder(){
Format formatter = new SimpleDateFormat("MMM-dd-yyyy");
String folderName = repo + formatter.format(new Date());
System.out.println("Folder Name :: "+folderName);
File file = new File(folderName);
if(!file.exists()){
file.mkdir();
}
return folderName;
}
public static void doDownload(String blogURL, String fileName) throws IOException {
String charset = "utf-8";
URL url = new URL(blogURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
InputStream inputStream = null;
inputStream = url.openStream();
StringBuffer s = new StringBuffer();
if(charset==null"".equals(charset)){
charset="utf-8"; }
String rLine = null;
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream,charset));
PrintWriter printWriter = null;
FileOutputStream fo = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8");
printWriter = new PrintWriter(writer);
while ( (rLine = bReader.readLine()) != null) {
String line = rLine;
int str_len = line.length();
if (str_len > 0) {
s.append(line);
printWriter.println(line);
printWriter.flush();
}
line = null;
}
inputStream.close();
printWriter.close();
}
}

You can change the repository folder name, I used here "E:\\Blog_BACKUP\\";
Whenever you will run this java code, it will create folder as running date and inside that folder your all blog backup will come with timestamp.

Please share your comments with me ........... :)

2. Another way
Step1 : Login to your blog (http://www.blogger.com)
Step2: Go to Setting tab
Step3: You will get Blog Tools (Upper left side)
Step4: Right side option are there like Import blogs, Export blogs, Delete blogs.

String.replaceAll not working, solution here

Sometime we get Exception in thread "main" java.util.regex.PatternSyntaxException during String.replaceAll() using.
When I used this code :

public void replaceString(String path){
System.out.println("Original Path :: "+path);
String ret = path.replaceAll("\\","/");
System.out.println("Return :: "+ret);
}
I got this exception
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1.


So for my project I am using this below custome method by the replaceAll method.


public void replaceString(String path){
System.out.println("Original Path :: "+path);
String ret = replaceAllString(path,"\\","/");
System.out.println("Return :: "+ret);
//return ret;
}
public String replaceAllString(String strOrig, String strFind, String strReplace) {
if(strOrig == null) {
return null;
}
StringBuffer sb = new StringBuffer(strOrig);
String toReplace = "";
if (strReplace == null) toReplace = "";
else toReplace = strReplace;
int pos = strOrig.length();
while (pos > -1) {
pos = strOrig.lastIndexOf(strFind, pos);
if (pos > -1) sb.replace(pos, pos+strFind.length(), toReplace);
pos = pos - strFind.length();
}
return sb.toString();
}

Its working fine for my project.

Monday, May 11, 2009

How to use Runtime.getRuntime().exec, How to solve java.io.IOException, error 2, Use Dos command in Java

This below code is very perfect to use Runtime.getRuntime().exec in windows platform as well as unix platform. You will not get ioexception error2 using this code.

Here, there are three method. Out of these first two you can put in common java file. Three is calling method to execute any dos commnad.

public Boolean exec(String[] command) {
Process proc;
StringBuffer cmdStr= new StringBuffer();
for(int i=0; icmdStr.append(command[i].trim());
if(i!=command.length-1){
cmdStr.append(" ");
}
}
try {
proc = Runtime.getRuntime().exec(cmdStr.toString());
} catch (IOException e) {
System.out.println("EXCEPTION_IO" + command);
System.out.println("EXCEPTION_TRACE"+ e);
return new Boolean(false);
}
int exitStatus;
while (true) {
try {
exitStatus = proc.waitFor();
break;
} catch (java.lang.InterruptedException e) {
System.out.println("EXCEPTION_TRACE"+ e);
}
}
if (exitStatus == 0) {
InputStream is = proc.getInputStream();
readStreamData(is);
}
if (exitStatus != 0) {
InputStream e = proc.getErrorStream();
String error = readStreamData(e);
System.out.println("ERROR_COMMAND"+ error);
}
return new Boolean(exitStatus == 0);
}

private static String readStreamData(InputStream e) {
BufferedInputStream bre = new BufferedInputStream(e);
String output = new String(" ");
try {
int readInt = bre.read();
while (readInt != -1) {
char c = (char) readInt;
output = output + c;
readInt = bre.read();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output;
}


public void copyFile(){
String sourceFile = "c:\\abcd\\mainImage\\DSC01596.JPG";
String destFile = "C:\\BackupImage\\Home";
List command = new ArrayList();
command.add("cmd.exe");
command.add("/c");
command.add("copy");
command.add(sourceFile);
command.add(destFile);
System.out.println("Executing Command :: " + command);
if(exec((String[]) command.toArray(new String[1]))){
System.out.println("Copied Successfully");
}
else{
System.out.println("Some Problem during copy");
}
}