Saturday, June 1, 2013

How To Convert String To Byte Array And Vice Versa In Java ?

How To Convert String To Byte Array In Java ?

The getBytes() method can be used to convert a String into byte array. An Example is given below:

String secret = "The Gold Is In Room 345";
 byte[] secretInBytes=secret.getBytes();


How To Convert Byte array To String In Java?

To convert the string back to byte array use new String(byteArrayName)

byte[] arr ; ----> Suppose 'arr' is a byte array
String str=new String(a); -------> Converts the byte array 'arr' to String

Java Program To Convert Image To Byte Array And Vice Versa

Java Program To Convert Image To Byte Array And Vice Versa

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import java.nio.file.Files;
class ByteToImage{
public static void main (String[] a)throws IOException{

 // Convert Image To Byte Array

 File fi = new File("rainforest.jpg");
 byte[] imageInBytes = Files.readAllBytes(fi.toPath());

 //Convert Byte Array To Image

 InputStream in = new ByteArrayInputStream(imageInBytes);
 BufferedImage b = ImageIO.read(in);
  ImageIO.write(b, "jpg", new File("rainforest1.jpg"));
}
}

Friday, May 31, 2013

error: possible loss of precision required: byte found: int

error: possible loss of precision required
required: byte found: int

This error can be overcome by doing a simple typecast as follows:

byte a,b,c;
c= (byte) (a+b); ----> This is because addition of 'byte' data type returns integer.
                                    So a typecast is a must

Very importantly include ( ) around a+b or any other calculation that you do.

What To Do If Size of Array Is Not Known Initially In Java?

What To Do If Size of Array Is Not Known Initially In Java?
(or)
How to dynamically allocate array in Java ?

To dynamically allocate array in Java, use the copyOf () method of Arrays class. Let us consider an example Java program to read numbers from the user until -1 is pressed. So initially, the size of array is not known. So let me create a 1 element array. For explanation, I am using int arrray.

int[] arr= new int[1];  ------> Initially, the array size is set to 1
System.out.println("Enter the items and press -1 to Quit");
if(i>1){
       arr=Arrays.copyOf(arr,arr.length+1); ------->Use copyOf function of java.util.Arrays class
}
arr[i]=s.nextInt(); // s is the object of java.util.Scanner class

Thursday, May 30, 2013

How To Convert JPEG Image Into Byte Array Using Java Program?

The Java program given below converts a jpeg image into a byte array :

import java.nio.file.Files;
import java.io.File;
import java.util.Arrays;
import java.io.IOException;
class ImageToByte
{
public static void main(String args[])throws IOException
{

File fi = new File("puppy.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath());
System.out.println(Arrays.toString(fileContent));

}
}

Tuesday, May 28, 2013

FileReader - How Can I Reset The File Pointer to the Beginning of the File in Java?

FileReader - How Can I Reset The File Pointer to the Beginning of the File in Java? 
(or)
Mark() and reset() not supported error for FileReader Class ?!?

The answer is just one line : You cannot work with mark() and reset() methods with FileReader. DON'T WORRY. You
have a one line solution to make it worked out.

Suppose your code is similar to the one shown below and you are trying with mark() and reset() as shown here:

FileReader file=new FileReader("apple.txt");
file.mark(25);
while((ch=file.read())!=-1)
Sytem.out.print((char) ch);
file.reset();

And you will get error like: "mark() not supported

So, the solution is using BufferedReader which supports both mark() and reset(). See the following code
 snippet on how to do modifications in your code.

FileReader file=new FileReader("apple.txt");
BufferedReader b=new BufferedReader(file);
b.mark(25);
while((ch=b.read())!=-1)
Sytem.out.print((char) ch);
b.reset();

Friday, May 24, 2013

Extracting File Name from File Path using StringTokenizer in Java

import java.util.Scanner;
import java.util.StringTokenizer;
public class ExtractName {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Enter the File Name with Location");
    Scanner input=new Scanner(System.in);
    String filePath=input.nextLine();
    String fileName=null;
    StringTokenizer tokens=new StringTokenizer(filePath,"\\");
    while (tokens.hasMoreElements()) {
fileName=null;
    fileName=(String) tokens.nextElement();
    }
    System.out.println("The File Name is "+fileName);
    input.close();
}

}

Java Source Coded to read and write into a file character by character

The following source code is an example of how to read and write the content of a file character-by-character to another file. This is also an example of how to give the file name as an input at the command prompt :


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ReadWrite {

public static void main(String[] args)throws IOException {
FileReader fileInput = null;
        FileWriter fileOutput = null;
        Scanner input;
        try
        {
        System.out.println("Enter the File Name with Location");
        input=new Scanner(System.in);
        String filePath=input.nextLine();
        fileInput = new FileReader(filePath);
            fileOutput = new FileWriter("C:\\Untitled1.txt");
            int character;
            while ((character = fileInput.read()) != -1) {
                fileOutput.write(character);
            }
        }
        catch (IOException e)
        {
            System.out.println("Error message: " + e.getMessage());
        }  
        finally
        {
           
            if (fileInput != null)
            fileInput.close();        
            if (fileInput != null)
            fileOutput.close();    
       }
  }
}

Wednesday, July 18, 2012

Installing Java in your computer

One second.. Before installing java in your computer make sure you don't have Java already installed.

Step 1: Check for Java in your computer :Simply double click My Computer and go to C->Program Files. If you can see a Java folder there, feel happy you may have Java installed. Still to make sure double click the Java folder and search for some jdk1.x.x [x is just a version number]. Double click it and there you can find a "bin" directory. Inside the bin directory search for "javac.exe" and "java.exe" files. If found really DONE!! javac.exe is the java compiler and java.exe is the java interpreter. So with them you can successfully run your program. Goto step3 directly

Step 2:  Install Java if not available in your computer : Type "http://www.oracle.com/technetwork/java/javase/downloads/index.html" in your browser.


Click download Java Platform (JDK). The following screen appears where you accept the license and click the jdk for your machine. I have windows - 32 bit OS. So I click on windows x86. [Note: windows x86 implies 32-bit OS]
The following window appears next:

Click Run . The following window appears:
The following window appears where you press run:

The below window appears:
Click Next button. Then the window shown below appears. You are going to develop java program. So make sure 'Development Tools' has been selected.
Click Next. The installation by default places the java inside your C:\Program Files. Now you go to my computer-> C-> Program Files, you can find it there. Done!!! Inside Java->jdk->bin, you can find the javac [java compiler] executable file and java[interpretor] executable file. So with these tools you can develop java program!!

Any doubts, you can ask me

Step 3: Create a folder into a drive you wish, say D:\; Let the folder name be myJavaCollection. Now lets start with the java program

Open notepad and type the following code there:
class Sample
{
     public static void main(String[] a){
         System.out.println("HELLO WORLD");
     }
}

Now save the notepad content. Click save and the name of the file should be entered as Sample.java. It is to be noted that the class name ( here Sample) and the name under which you save must be same. The .java file extension is also mandatory. The above program must be saved as Sample.java

Step 4: Now its time to compile and run your java code. As I told before, to compile a java program you need a java compiler. You can find this java compiler inside c:\program files\java\jdk1.x.x\bin. Inside bin can you find many .exe files. There you can see javac.exe and java.exe files. javac is used to compile your source code and it produces a class file [which is not an object file. it is just a bytecode]. java is the interpreter that you can use to execute your bytecode.

Now open the command prompt in your system. Run->cmd

Now change to the directory where you saved your program [here, Sample.java]. Suppose the directory is D, enter d: and press enter. You can see that the command prompt is changed to the d: drive. Now enter cd myJavaCollection and press enter.

Step 5: Now just type javac in your command prompt to find whether your OS could recognize the compiler. If it couldn't recognise, it displays an error message as shown below: 'javac' is not recognized.


Don't worry. Lets make the compiler to be visible to the Operating system. Assuming you are using Windows OS, follow the steps given below:
a)Right Click My Computer and select Properties


First click on the advanced tab and then on the Environment Variables.

The following window appears:
Click on the New button highlighted in the above figure. Then you get a small panel window as shown:
For the Variable name, give PATH.For the Variable value, give the path of your javac and java tools. In my example it is C:\Program Files\Java\jdk1.7.0\bin. Please, dont copy and paste this path. Go to your system drives and locate the of bin and paste there.
It is very IMPORTANT : Close the already opened cmd prompt window because the path set in the environmental variable wont be reflected in the already opened command prompt. Open another command prompt. Run-> cmd .

Now compile your java program using javac Sample.java
Then run your program java Sample