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();    
       }
  }
}