How do I convert a File into an array of bytes?

M

MattC

I have a File object that represents a file on the file system. I want
to use that File to obtain a an array of bytes (byte[]). Can someone
tell me how to do this?

Thanks
 
R

Roedy Green

I have a File object that represents a file on the file system. I want
to use that File to obtain a an array of bytes (byte[]). Can someone
tell me how to do this?

See http://mindprod.com/applets/fileio.html

tell it you want to read raw bytes, unbuffered from a file.

Then read the entire file into a byte array File.length() bytes long
in one fell swoop.
 
V

Viv

package Practice;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class Temp {

public static void main(String[] args)
{
File file = new File("c:/EventItemBroker.java");

byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
e1.printStackTrace();
}

}
}
 
Joined
May 13, 2010
Messages
1
Reaction score
0
Viv said:
package Practice;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class Temp {

public static void main(String[] args)
{
File file = new File("c:/EventItemBroker.java");

byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char)b);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
e1.printStackTrace();
}

}
}

Hello,

I have tested the above code and It is Working absolutely fine.

However, When I try to stream a PDF file from my File system, The program works fine, But the output seems to be encoded and Data needed cannot be read.

Is it the File format, i.e. PDF, that makes this code to read the file the way it is?

How do i just read the contents of the PDF file without having to display all the other configuration data of the pdf file.. ?

Regards,
Vrandesh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top