how to convert file into binary using java - java

try
{
FileInputStream fis=new FileInputStream(new File("Binary.txt"));
byte[] infoBin=new byte[fis.available()];
fis.read(infoBin);
for (byte b : infoBin)
{
String bin=Integer.toBinaryString(b);
}
}
How to read a file and convert that file contents into binary then write the binary to a new file using java
After Binary conversion, i don't know how to write the string bin into the new file ?

//reading from file
byte[] array = Files.readAllBytes(Paths.get("Binary.txt"));
//saving to file
FileOutputStream fos = new FileOutputStream("Binary.txt");
fos.write(array );
fos.close();

How to read a file and convert that file contents into binary
They already are binary.
then write the binary to a new file using java
There's no need to waste memory, or assume the file fits into memory, or assume the file size fits into an int. Memorise the following loop for copying between streams in Java:
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}

Related

How to read n base64 encoded characters from a file at a time and decode and write to another file?

Currently I have a source file which has base64 encoded data (20 mb in size approx). I want to read from this file, decode the data and write to a .TIF output file. However I don't want to decode all 20MB data at once. I want to read a specific number of characters/bytes from the source file, decode it and write to destination file. I understand that the size of the data I read from the source file has to be in multiples of 4 or else it can't be decoded?
Below is my current code where I decode it all at once
public write Output(File file){
BufferedReader br = new BufferedReader (new Filereader(file));
String builder sb = new StringBuilder ();
String line=BR.readLine();
While(line!=null){
....
//Read line by line and append to sb
}
byte[] decoded = Base64.getMimeDecoder().decode(SB.toString());
File outputFile = new File ("output.tif")
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
out.write(decoded);
out.flush();
}
How can I read specific number of characters from source file and decode and then write to output file so I don't have to load everything in memory?
Here is a simple method to demonstrate doing this, by wrapping the Base64 Decoder around an input stream and reading into an appropriately sized byte array.
public static void readBase64File(File inputFile, File outputFile, int chunkSize) throws IOException {
FileInputStream fin = new FileInputStream(inputFile);
FileOutputStream fout = new FileOutputStream(outputFile);
InputStream base64Stream = Base64.getMimeDecoder().wrap(fin);
byte[] chunk = new byte[chunkSize];
int read;
while ((read = base64Stream.read(chunk)) != -1) {
fout.write(chunk, 0, read);
}
fin.close();
fout.close();
}

Merging RTF files?

I'm using Java and I need to append, concat, merge or add, whichever is the right term, two .rtf files together in its original format for both rtf files, into one rtf file. Each of the rtf files are a page long, so I need to create a two page rtf file, from the two files.
I also need to create a page break between the two files, in the new combined rtf file. I went to MS word and was able to combine the two rtf files together, but that just created a long rtf file with no page break.
I have a code, but it only copies one file to another file in the same way, but I need help on tweaking out this code so I can copy two files into one file
FileInputStream file = new FileInputStream("old.rtf");
FileOutputStream out = new FileOutputStream("new.rtf");
byte[] buffer = new byte[1024];
int count;
while ((count= file.read(buffer)) > 0)
out.write(buffer, 0, count);
How do I add another FileInputStream object on top of the FileInputStream file, into FileOutputStream out, with a page break between file and object?
I am totally stuck. I was able to combine the two rtf files with help, but could not keep the original format of the two rtf file into the new one.
I tried the :
FileInputStream file = new FileInputStream("old.rtf");
FileOutputStream out = new FileOutputStream("new.rtf", true);
byte[] buffer = new byte[1024];
int count;
while ((count= file.read(buffer)) > 0)
out.write(buffer, 0, count);
FileOutputStream(File file, boolean append), where the old.rtf is suppose to append to new.rtf, but when I do it, the old.rtf is just written into the new.rtf.
What am I doing wrong?
When you open the file you wish to add to, use the FileOutputStream(File file, boolean append) with append set to true, then you can add to the new file, rather than over write it.
FileInputStream file = new FileInputStream("old.rtf");
FileOutputStream out = new FileOutputStream("new.rtf", true);
byte[] buffer = new byte[1024];
int count;
while ((count= file.read(buffer)) > 0)
out.write(buffer, 0, count);
This will append old.rtf to new.rtf.
You can also do:
FileInputStream file = new FileInputStream("old1.rtf");
FileOutputStream out = new FileOutputStream("new.rtf");
byte[] buffer = new byte[1024];
int count;
while ((count= file.read(buffer)) > 0)
out.write(buffer, 0, count);
file.close();
file = new FileOutputStream("old2.rtf");
while ((count= file.read(buffer)) > 0)
out.write(buffer, 0, count);
That will concatenate old1.rtf and old2.rtf to the new file new.rtf.

Opening an image file from java InputStream

I am trying to open an image file that is packaged in a .jar file using the default image viewer of the computer on which i run my program.
I have found numerous answers about how to access files that are packaged in a jar using InputStream but how can i open those files using that InputStream?
InputStream imageStream = Test.class.getClass().getResourceAsStream("/test/DSC_6283.jpg");
I can convert this into an Image, ImageIcon or a BufferedImage but how to i further open the image in the default image viewer?
My class name is 'Test' and the image i am trying to access is C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg
Any help would be appreciated.
Pure java:
public static void main(String... args) throws IOException {
InputStream imageStream = Test.class.getClass().getResourceAsStream("/test/DSC_6283.jpg");
Path path = Files.createTempFile("DSC_6283", ".jpg");
try (FileOutputStream out = new FileOutputStream(path.toFile())) {
byte[] buffer = new byte[1024];
int len;
while ((len = imageStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
// TODO: handle exception
}
Desktop.getDesktop().open(path.toFile());
}
Edit:
byte[] buffer = new byte[1024]; //allocate an array of bytes to use as a buffer. 1024 bytes in this case
int len; //a variable to record the number of bytes actually read from the stream each loop
while ((len = imageStream.read(buffer)) != -1) { //InputStream.read(byte[]) reads bytes from the stream and places them into the buffer. It returns the number of bytes placed into the buffer, or -1 if there is nothing more to read. We store that result in len, and evaluate if we should stop looping (ie if the return is -1)
out.write(buffer, 0, len); //write to the output file, from the buffer, starting at position 0, through the number of bytes read
Note, this is boilerplate. I stole this version from Easy way to write contents of a Java InputStream to an OutputStream
Save the image locally (ex. c:\my_image.jpg), which is not in the .jar file
Use Runtime.getRuntime().exec("cmd your_command_here_to_open_image");
here is a link for cmd command on windows: http://www.sevenforums.com/software/180378-where-windows-photo-viewer-default-location.html

Transferring file in client-server program but all bytes not being transmitted

I am currently writing a client-server program that would allow me to upload a file from the client to the server. However, when I try this the file becomes corrupt and it appears not all the bytes are being transferred. Can someone tell me why this is happening? Thanks.
Here is part of the client code:
System.out.println("What file would you like to upload?");
String file=in.next();//get file name
outToServer.writeUTF(file);//send file name to server
File test= new File(file);//create file
byte[] bits = new byte[(int) test.length()]; //byte array to store file
FileInputStream fis= new FileInputStream(test); //read in file
//write bytes into array
int size=(int) test.length();//size of array
outToServer.write(size);//send size of array to Server
fis.read(bits);//read in byte values
fis.close();//close stream
outToServer.write(bits, 0, size);//writes bytes out to server
And here is the server code:
String filename= inFromClient.readUTF();//read in file name that is being uploaded
int size=inFromClient.read(); //read in size of file
byte[] bots=new byte[size]; //create array
inFromClient.read(bots); //read in bytes
FileOutputStream fos=new FileOutputStream(filename);
fos.write(bots);
fos.flush();
fos.close();
String complete="Upload Complete.";
outToClient.writeUTF(complete);
Try and use Java 7's Files.copy().
On the client side:
final Path source = Paths.get(file);
Files.copy(source, outToServer);
On the server side:
final Path destination = Paths.get(file);
Files.copy(inFromClient, destination);
See the javadoc for Files.
Usual mistake. You're assuming that read() fills the buffer. It isn't obliged to do that. See the Javadoc.
The canonical way to copy streams in Java is as follows:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Use this at both ends. You don't need a buffer the size of the file either. This works for any byte array with one or more elements.

Can I create a byte[] straight from a folder?

A web Service expects a byte[] coming from a zip file.
I have some files in a folder that I zip with Java and then I get the byte[] from this zip file.
Is this necessary or can I create the byte[] straight from the folder?
I think something like this would allow you to do what you want without writing as long as the files are not going to be very big.
String[] sourceFiles = { "C:/file1", "C:/file2" };
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zout = new ZipOutputStream(baos);
byte[] buffer = new byte[4096];
for (int i = 0; i < sourceFiles.length; i++)
{
FileInputStream fin = new FileInputStream(sourceFiles[i]);
zout.putNextEntry(new ZipEntry(sourceFiles[i]));
int length;
while ((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
zout.close();
byte[] bytes = baos.toByteArray();
A folder is a collection of files. It is a container. It does not have a byte stream to get in the first place.
On the other hand, a ZIP (or any archive) is a file. The information about the different files is stored within the ZIP file itself
However, you can iterate through the folder contents, cook up a byte array and then use it (you are doing that anyways while creating the ZIP).

Categories

Resources